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