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