eb44b4997ff06982f23a0373f970564ca0879738
[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 #include <boost/make_shared.hpp>
55
56 #ifdef check
57 #undef check
58 #endif
59
60 using std::exception;
61 using std::list;
62 using std::string;
63 using std::vector;
64 using boost::shared_ptr;
65 using boost::make_shared;
66 using boost::bind;
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
82 static string
83 column (dcp::EncryptedKDM k)
84 {
85         return String::compose ("%1 (%2)", k.content_title_text(), k.cpl_id());
86 }
87
88 class DOMFrame : public wxFrame
89 {
90 public:
91         DOMFrame (wxString const & title)
92                 : wxFrame (0, -1, title)
93                 , _config_dialog (0)
94                 , _job_view (0)
95         {
96 #if defined(DCPOMATIC_WINDOWS)
97                 if (Config::instance()->win32_console ()) {
98                         AllocConsole();
99
100                         HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
101                         int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
102                         FILE* hf_out = _fdopen(hCrt, "w");
103                         setvbuf(hf_out, NULL, _IONBF, 1);
104                         *stdout = *hf_out;
105
106                         HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
107                         hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
108                         FILE* hf_in = _fdopen(hCrt, "r");
109                         setvbuf(hf_in, NULL, _IONBF, 128);
110                         *stdin = *hf_in;
111
112                         std::cout << "DCP-o-matic KDM creator is starting." << "\n";
113                 }
114 #endif
115
116                 wxMenuBar* bar = new wxMenuBar;
117                 setup_menu (bar);
118                 SetMenuBar (bar);
119
120                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::file_exit, this),             wxID_EXIT);
121                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::edit_preferences, this),      wxID_PREFERENCES);
122                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::help_about, this),            wxID_ABOUT);
123                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::help_report_a_problem, this), ID_help_report_a_problem);
124
125                 /* Use a panel as the only child of the Frame so that we avoid
126                    the dark-grey background on Windows.
127                 */
128                 wxPanel* overall_panel = new wxPanel (this, wxID_ANY);
129                 wxBoxSizer* main_sizer = new wxBoxSizer (wxHORIZONTAL);
130
131                 wxBoxSizer* vertical = new wxBoxSizer (wxVERTICAL);
132
133                 wxFont subheading_font (*wxNORMAL_FONT);
134                 subheading_font.SetWeight (wxFONTWEIGHT_BOLD);
135
136                 wxStaticText* h = new wxStaticText (overall_panel, wxID_ANY, _("Screens"));
137                 h->SetFont (subheading_font);
138                 vertical->Add (h, 0, wxALIGN_CENTER_VERTICAL);
139                 _screens = new ScreensPanel (overall_panel);
140                 vertical->Add (_screens, 1, wxEXPAND | wxALL, DCPOMATIC_SIZER_Y_GAP);
141
142                 _timing = new KDMTimingPanel (overall_panel);
143                 vertical->Add (_timing, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
144
145                 h = new wxStaticText (overall_panel, wxID_ANY, _("DKDM"));
146                 h->SetFont (subheading_font);
147                 vertical->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxTOP, DCPOMATIC_SIZER_Y_GAP * 2);
148
149                 vector<string> columns;
150                 columns.push_back (wx_to_std (_("CPL")));
151                 _dkdm = new EditableList<dcp::EncryptedKDM, KDMFileDialogWrapper> (
152                         overall_panel, columns, bind (&DOMFrame::dkdms, this), bind (&DOMFrame::set_dkdms, this, _1), bind (&always_valid), bind (&column, _1), false
153                         );
154                 vertical->Add (_dkdm, 0, wxEXPAND | wxALL, DCPOMATIC_SIZER_Y_GAP);
155
156                 h = new wxStaticText (overall_panel, wxID_ANY, _("Output"));
157                 h->SetFont (subheading_font);
158                 vertical->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxTOP, DCPOMATIC_SIZER_Y_GAP * 2);
159                 /* XXX: hard-coded non-interop here */
160                 _output = new KDMOutputPanel (overall_panel, false);
161                 vertical->Add (_output, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
162
163                 _create = new wxButton (overall_panel, wxID_ANY, _("Create KDMs"));
164                 vertical->Add (_create, 0, wxALL, DCPOMATIC_SIZER_GAP);
165
166                 main_sizer->Add (vertical, 1, wxALL | wxEXPAND, DCPOMATIC_DIALOG_BORDER);
167                 overall_panel->SetSizer (main_sizer);
168
169                 /* Instantly save any config changes when using a DCP-o-matic GUI */
170                 Config::instance()->Changed.connect (boost::bind (&Config::write, Config::instance ()));
171
172                 _screens->ScreensChanged.connect (boost::bind (&DOMFrame::setup_sensitivity, this));
173                 _create->Bind (wxEVT_COMMAND_BUTTON_CLICKED, bind (&DOMFrame::create_kdms, this));
174                 _dkdm->SelectionChanged.connect (boost::bind (&DOMFrame::setup_sensitivity, this));
175
176                 setup_sensitivity ();
177         }
178
179 private:
180         vector<dcp::EncryptedKDM> dkdms () const
181         {
182                 return Config::instance()->dkdms ();
183         }
184
185         void set_dkdms (vector<dcp::EncryptedKDM> dkdms)
186         {
187                 Config::instance()->set_dkdms (dkdms);
188         }
189
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         void create_kdms ()
253         {
254                 try {
255                         if (!_dkdm->selection()) {
256                                 return;
257                         }
258
259                         /* Decrypt the DKDM */
260                         dcp::DecryptedKDM decrypted (_dkdm->selection().get(), Config::instance()->decryption_chain()->key().get());
261
262                         /* This is the signer for our new KDMs */
263                         shared_ptr<const dcp::CertificateChain> signer = Config::instance()->signer_chain ();
264                         if (!signer->valid ()) {
265                                 throw InvalidSignerError ();
266                         }
267
268                         list<ScreenKDM> screen_kdms;
269                         BOOST_FOREACH (shared_ptr<Screen> i, _screens->screens()) {
270
271                                 if (!i->recipient) {
272                                         continue;
273                                 }
274
275                                 /* Make an empty KDM */
276                                 dcp::DecryptedKDM kdm (
277                                         dcp::LocalTime (_timing->from(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
278                                         dcp::LocalTime (_timing->until(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
279                                         decrypted.annotation_text().get_value_or (""),
280                                         decrypted.content_title_text(),
281                                         dcp::LocalTime().as_string()
282                                         );
283
284                                 /* Add keys from the DKDM */
285                                 BOOST_FOREACH (dcp::DecryptedKDMKey const & j, decrypted.keys()) {
286                                         kdm.add_key (j);
287                                 }
288
289                                 /* Encrypt */
290                                 screen_kdms.push_back (ScreenKDM (i, kdm.encrypt (signer, i->recipient.get(), i->trusted_devices, _output->formulation())));
291                         }
292
293                         if (_output->write_to()) {
294                                 ScreenKDM::write_files (decrypted.content_title_text(), screen_kdms, _output->directory());
295                                 /* XXX: proper plural form support in wxWidgets? */
296                                 wxString s = screen_kdms.size() == 1 ? _("%d KDM written to %s") : _("%d KDMs written to %s");
297                                 message_dialog (
298                                         this,
299                                         wxString::Format (s, int(screen_kdms.size()), std_to_wx(_output->directory().string()).data())
300                                         );
301                         } else {
302                                 string film_name = decrypted.annotation_text().get_value_or ("");
303                                 if (film_name.empty ()) {
304                                         film_name = decrypted.content_title_text ();
305                                 }
306                                 shared_ptr<Job> job = boost::make_shared<SendKDMEmailJob> (
307                                         film_name,
308                                         decrypted.content_title_text(),
309                                         _timing->from(), _timing->until(),
310                                         CinemaKDMs::collect (screen_kdms),
311                                         shared_ptr<Log> ()
312                                         );
313
314                                 JobManager::instance()->add (job);
315                                 if (_job_view) {
316                                         _job_view->Destroy ();
317                                         _job_view = 0;
318                                 }
319                                 _job_view = new JobViewDialog (this, _("Send KDM emails"), job);
320                                 _job_view->ShowModal ();
321                         }
322                 } catch (dcp::NotEncryptedError& e) {
323                         error_dialog (this, _("CPL's content is not encrypted."));
324                 } catch (exception& e) {
325                         error_dialog (this, e.what ());
326                 } catch (...) {
327                         error_dialog (this, _("An unknown exception occurred."));
328                 }
329         }
330
331         void setup_sensitivity ()
332         {
333                 _screens->setup_sensitivity ();
334                 _output->setup_sensitivity ();
335                 _create->Enable (!_screens->screens().empty() && _dkdm->selection());
336         }
337
338         wxPreferencesEditor* _config_dialog;
339         ScreensPanel* _screens;
340         KDMTimingPanel* _timing;
341         EditableList<dcp::EncryptedKDM, KDMFileDialogWrapper>* _dkdm;
342         wxButton* _create;
343         KDMOutputPanel* _output;
344         JobViewDialog* _job_view;
345 };
346
347 /** @class App
348  *  @brief The magic App class for wxWidgets.
349  */
350 class App : public wxApp
351 {
352 public:
353         App ()
354                 : wxApp ()
355                 , _frame (0)
356         {}
357
358 private:
359
360         bool OnInit ()
361         try
362         {
363                 wxInitAllImageHandlers ();
364
365                 SetAppName (_("DCP-o-matic KDM Creator"));
366
367                 if (!wxApp::OnInit()) {
368                         return false;
369                 }
370
371 #ifdef DCPOMATIC_LINUX
372                 unsetenv ("UBUNTU_MENUPROXY");
373 #endif
374
375 #ifdef __WXOSX__
376                 ProcessSerialNumber serial;
377                 GetCurrentProcess (&serial);
378                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
379 #endif
380
381                 dcpomatic_setup_path_encoding ();
382
383                 /* Enable i18n; this will create a Config object
384                    to look for a force-configured language.  This Config
385                    object will be wrong, however, because dcpomatic_setup
386                    hasn't yet been called and there aren't any filters etc.
387                    set up yet.
388                 */
389                 dcpomatic_setup_i18n ();
390
391                 /* Set things up, including filters etc.
392                    which will now be internationalised correctly.
393                 */
394                 dcpomatic_setup ();
395
396                 /* Force the configuration to be re-loaded correctly next
397                    time it is needed.
398                 */
399                 Config::drop ();
400
401                 _frame = new DOMFrame (_("DCP-o-matic KDM Creator"));
402                 SetTopWindow (_frame);
403                 _frame->Maximize ();
404                 _frame->Show ();
405
406                 signal_manager = new wxSignalManager (this);
407                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
408
409                 return true;
410         }
411         catch (exception& e)
412         {
413                 error_dialog (0, wxString::Format ("DCP-o-matic could not start: %s", e.what ()));
414                 return true;
415         }
416
417         /* An unhandled exception has occurred inside the main event loop */
418         bool OnExceptionInMainLoop ()
419         {
420                 try {
421                         throw;
422                 } catch (FileError& e) {
423                         error_dialog (
424                                 0,
425                                 wxString::Format (
426                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
427                                         std_to_wx (e.what()),
428                                         std_to_wx (e.file().string().c_str ())
429                                         )
430                                 );
431                 } catch (exception& e) {
432                         error_dialog (
433                                 0,
434                                 wxString::Format (
435                                         _("An exception occurred: %s.\n\n") + " " + REPORT_PROBLEM,
436                                         std_to_wx (e.what ())
437                                         )
438                                 );
439                 } catch (...) {
440                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
441                 }
442
443                 /* This will terminate the program */
444                 return false;
445         }
446
447         void OnUnhandledException ()
448         {
449                 error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
450         }
451
452         void idle ()
453         {
454                 signal_manager->ui_idle ();
455         }
456
457         DOMFrame* _frame;
458 };
459
460 IMPLEMENT_APP (App)