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