Basic implementation of a tree view for DKDMs (#1012).
[dcpomatic.git] / src / tools / dcpomatic_kdm.cc
1 /*
2     Copyright (C) 2015-2017 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/new_dkdm_folder_dialog.h"
33 #include "wx/editable_list.h"
34 #include "lib/config.h"
35 #include "lib/util.h"
36 #include "lib/screen.h"
37 #include "lib/job_manager.h"
38 #include "lib/screen_kdm.h"
39 #include "lib/exceptions.h"
40 #include "lib/cinema_kdms.h"
41 #include "lib/send_kdm_email_job.h"
42 #include "lib/compose.hpp"
43 #include "lib/cinema.h"
44 #include "lib/dkdm_wrapper.h"
45 #include <dcp/encrypted_kdm.h>
46 #include <dcp/decrypted_kdm.h>
47 #include <dcp/exceptions.h>
48 #include <wx/wx.h>
49 #include <wx/preferences.h>
50 #include <wx/filepicker.h>
51 #ifdef __WXOSX__
52 #include <ApplicationServices/ApplicationServices.h>
53 #endif
54 #include <boost/bind.hpp>
55 #include <boost/foreach.hpp>
56
57 #ifdef check
58 #undef check
59 #endif
60
61 using std::exception;
62 using std::list;
63 using std::string;
64 using std::vector;
65 using std::pair;
66 using std::map;
67 using boost::shared_ptr;
68 using boost::bind;
69 using boost::optional;
70 using boost::ref;
71 using boost::dynamic_pointer_cast;
72
73 enum {
74         ID_help_report_a_problem = 1,
75 };
76
77 class DOMFrame : public wxFrame
78 {
79 public:
80         DOMFrame (wxString const & title)
81                 : wxFrame (0, -1, title)
82                 , _config_dialog (0)
83                 , _job_view (0)
84         {
85 #if defined(DCPOMATIC_WINDOWS)
86                 if (Config::instance()->win32_console ()) {
87                         AllocConsole();
88
89                         HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
90                         int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
91                         FILE* hf_out = _fdopen(hCrt, "w");
92                         setvbuf(hf_out, NULL, _IONBF, 1);
93                         *stdout = *hf_out;
94
95                         HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
96                         hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
97                         FILE* hf_in = _fdopen(hCrt, "r");
98                         setvbuf(hf_in, NULL, _IONBF, 128);
99                         *stdin = *hf_in;
100
101                         std::cout << "DCP-o-matic KDM creator is starting." << "\n";
102                 }
103 #endif
104
105                 wxMenuBar* bar = new wxMenuBar;
106                 setup_menu (bar);
107                 SetMenuBar (bar);
108
109                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this),             wxID_EXIT);
110                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this),      wxID_PREFERENCES);
111                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this),            wxID_ABOUT);
112                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this), ID_help_report_a_problem);
113
114                 /* Use a panel as the only child of the Frame so that we avoid
115                    the dark-grey background on Windows.
116                 */
117                 wxPanel* overall_panel = new wxPanel (this, wxID_ANY);
118                 wxBoxSizer* main_sizer = new wxBoxSizer (wxHORIZONTAL);
119
120                 wxBoxSizer* horizontal = new wxBoxSizer (wxHORIZONTAL);
121                 wxBoxSizer* left = new wxBoxSizer (wxVERTICAL);
122                 wxBoxSizer* right = new wxBoxSizer (wxVERTICAL);
123
124                 horizontal->Add (left, 1, wxEXPAND | wxRIGHT, DCPOMATIC_SIZER_X_GAP * 2);
125                 horizontal->Add (right, 1, wxEXPAND);
126
127                 wxFont subheading_font (*wxNORMAL_FONT);
128                 subheading_font.SetWeight (wxFONTWEIGHT_BOLD);
129
130                 wxStaticText* h = new wxStaticText (overall_panel, wxID_ANY, _("Screens"));
131                 h->SetFont (subheading_font);
132                 left->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxBOTTOM, DCPOMATIC_SIZER_Y_GAP);
133                 _screens = new ScreensPanel (overall_panel);
134                 left->Add (_screens, 1, wxEXPAND | wxBOTTOM, DCPOMATIC_SIZER_Y_GAP);
135
136                 /// TRANSLATORS: translate the word "Timing" here; do not include the "KDM|" prefix
137                 h = new wxStaticText (overall_panel, wxID_ANY, S_("KDM|Timing"));
138                 h->SetFont (subheading_font);
139                 right->Add (h, 0, wxALIGN_CENTER_VERTICAL, DCPOMATIC_SIZER_Y_GAP * 2);
140                 _timing = new KDMTimingPanel (overall_panel);
141                 right->Add (_timing, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
142
143                 h = new wxStaticText (overall_panel, wxID_ANY, _("DKDM"));
144                 h->SetFont (subheading_font);
145                 right->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxTOP, DCPOMATIC_SIZER_Y_GAP * 2);
146                 wxBoxSizer* dkdm_sizer = new wxBoxSizer (wxHORIZONTAL);
147                 _dkdm = new wxTreeCtrl (
148                         overall_panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_HIDE_ROOT | wxTR_HAS_BUTTONS | wxTR_LINES_AT_ROOT
149                 );
150                 dkdm_sizer->Add (_dkdm, 1, wxEXPAND | wxALL, DCPOMATIC_SIZER_Y_GAP);
151                 wxBoxSizer* dkdm_buttons = new wxBoxSizer(wxVERTICAL);
152                 _add_dkdm = new wxButton (overall_panel, wxID_ANY, _("Add..."));
153                 dkdm_buttons->Add (_add_dkdm, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
154                 _add_dkdm_folder = new wxButton (overall_panel, wxID_ANY, _("Add folder..."));
155                 dkdm_buttons->Add (_add_dkdm_folder, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
156                 _remove_dkdm = new wxButton (overall_panel, wxID_ANY, _("Remove"));
157                 dkdm_buttons->Add (_remove_dkdm, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
158                 dkdm_sizer->Add (dkdm_buttons, 0, wxEXPAND | wxALL, DCPOMATIC_SIZER_GAP);
159                 right->Add (dkdm_sizer, 1, wxEXPAND | wxALL, DCPOMATIC_SIZER_Y_GAP);
160
161                 _dkdm_id[_dkdm->AddRoot("root")] = Config::instance()->dkdms();
162                 add_dkdm_view (Config::instance()->dkdms(), shared_ptr<DKDMGroup> ());
163
164                 h = new wxStaticText (overall_panel, wxID_ANY, _("Output"));
165                 h->SetFont (subheading_font);
166                 right->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxTOP, DCPOMATIC_SIZER_Y_GAP * 2);
167                 /* XXX: hard-coded non-interop here */
168                 _output = new KDMOutputPanel (overall_panel, false);
169                 right->Add (_output, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
170
171                 _create = new wxButton (overall_panel, wxID_ANY, _("Create KDMs"));
172                 right->Add (_create, 0, wxALL, DCPOMATIC_SIZER_GAP);
173
174                 main_sizer->Add (horizontal, 1, wxALL | wxEXPAND, DCPOMATIC_DIALOG_BORDER);
175                 overall_panel->SetSizer (main_sizer);
176
177                 /* Instantly save any config changes when using a DCP-o-matic GUI */
178                 Config::instance()->Changed.connect (boost::bind (&Config::write, Config::instance ()));
179
180                 _screens->ScreensChanged.connect (boost::bind (&DOMFrame::setup_sensitivity, this));
181                 _create->Bind (wxEVT_BUTTON, bind (&DOMFrame::create_kdms, this));
182                 _dkdm->Bind (wxEVT_TREE_SEL_CHANGED, boost::bind (&DOMFrame::setup_sensitivity, this));
183                 _add_dkdm->Bind (wxEVT_BUTTON, bind (&DOMFrame::add_dkdm_clicked, this));
184                 _add_dkdm_folder->Bind (wxEVT_BUTTON, bind (&DOMFrame::add_dkdm_folder_clicked, this));
185                 _remove_dkdm->Bind (wxEVT_BUTTON, bind (&DOMFrame::remove_dkdm_clicked, this));
186
187                 setup_sensitivity ();
188         }
189
190 private:
191         void file_exit ()
192         {
193                 /* false here allows the close handler to veto the close request */
194                 Close (false);
195         }
196
197         void edit_preferences ()
198         {
199                 if (!_config_dialog) {
200                         _config_dialog = create_config_dialog ();
201                 }
202                 _config_dialog->Show (this);
203         }
204
205         void help_about ()
206         {
207                 AboutDialog* d = new AboutDialog (this);
208                 d->ShowModal ();
209                 d->Destroy ();
210         }
211
212         void help_report_a_problem ()
213         {
214                 ReportProblemDialog* d = new ReportProblemDialog (this, shared_ptr<Film> ());
215                 if (d->ShowModal () == wxID_OK) {
216                         d->report ();
217                 }
218                 d->Destroy ();
219         }
220
221         void setup_menu (wxMenuBar* m)
222         {
223                 wxMenu* file = new wxMenu;
224
225 #ifdef __WXOSX__
226                 file->Append (wxID_EXIT, _("&Exit"));
227 #else
228                 file->Append (wxID_EXIT, _("&Quit"));
229 #endif
230
231 #ifdef __WXOSX__
232                 file->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
233 #else
234                 wxMenu* edit = new wxMenu;
235                 edit->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
236 #endif
237
238                 wxMenu* help = new wxMenu;
239 #ifdef __WXOSX__
240                 help->Append (wxID_ABOUT, _("About DCP-o-matic"));
241 #else
242                 help->Append (wxID_ABOUT, _("About"));
243 #endif
244                 help->Append (ID_help_report_a_problem, _("Report a problem..."));
245
246                 m->Append (file, _("&File"));
247 #ifndef __WXOSX__
248                 m->Append (edit, _("&Edit"));
249 #endif
250                 m->Append (help, _("&Help"));
251         }
252
253         bool confirm_overwrite (boost::filesystem::path path)
254         {
255                 return confirm_dialog (
256                         this,
257                         wxString::Format (_("File %s already exists.  Do you want to overwrite it?"), std_to_wx(path.string()).data())
258                         );
259         }
260
261         /** @id if not 0 this is filled in with the wxTreeItemId of the selection */
262         shared_ptr<DKDMBase> selected_dkdm (wxTreeItemId* id = 0) const
263         {
264                 wxArrayTreeItemIds selections;
265                 _dkdm->GetSelections (selections);
266                 if (selections.GetCount() != 1) {
267                         if (id) {
268                                 *id = 0;
269                         }
270                         return shared_ptr<DKDMBase> ();
271                 }
272
273                 if (id) {
274                         *id = selections[0];
275                 }
276
277                 DKDMMap::const_iterator i = _dkdm_id.find (selections[0]);
278                 if (i == _dkdm_id.end()) {
279                         return shared_ptr<DKDMBase> ();
280                 }
281
282                 return i->second;
283         }
284
285         void create_kdms ()
286         {
287                 try {
288                         shared_ptr<DKDMBase> dkdm_base = selected_dkdm ();
289                         if (!dkdm_base) {
290                                 return;
291                         }
292                         shared_ptr<DKDM> dkdm = boost::dynamic_pointer_cast<DKDM> (dkdm_base);
293                         if (!dkdm) {
294                                 return;
295                         }
296
297                         /* Decrypt the DKDM */
298                         dcp::DecryptedKDM decrypted (dkdm->dkdm(), Config::instance()->decryption_chain()->key().get());
299
300                         /* This is the signer for our new KDMs */
301                         shared_ptr<const dcp::CertificateChain> signer = Config::instance()->signer_chain ();
302                         if (!signer->valid ()) {
303                                 throw InvalidSignerError ();
304                         }
305
306                         list<ScreenKDM> screen_kdms;
307                         BOOST_FOREACH (shared_ptr<Screen> i, _screens->screens()) {
308
309                                 if (!i->recipient) {
310                                         continue;
311                                 }
312
313                                 /* Make an empty KDM */
314                                 dcp::DecryptedKDM kdm (
315                                         dcp::LocalTime (_timing->from(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
316                                         dcp::LocalTime (_timing->until(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
317                                         decrypted.annotation_text().get_value_or (""),
318                                         decrypted.content_title_text(),
319                                         dcp::LocalTime().as_string()
320                                         );
321
322                                 /* Add keys from the DKDM */
323                                 BOOST_FOREACH (dcp::DecryptedKDMKey const & j, decrypted.keys()) {
324                                         kdm.add_key (j);
325                                 }
326
327                                 /* Encrypt */
328                                 screen_kdms.push_back (ScreenKDM (i, kdm.encrypt (signer, i->recipient.get(), i->trusted_devices, _output->formulation())));
329                         }
330
331                         pair<shared_ptr<Job>, int> result = _output->make (
332                                 screen_kdms, decrypted.content_title_text(), _timing, bind (&DOMFrame::confirm_overwrite, this, _1), shared_ptr<Log> ()
333                                 );
334
335                         if (result.first) {
336                                 JobManager::instance()->add (result.first);
337                                 if (_job_view) {
338                                         _job_view->Destroy ();
339                                         _job_view = 0;
340                                 }
341                                 _job_view = new JobViewDialog (this, _("Send KDM emails"), result.first);
342                                 _job_view->ShowModal ();
343                         }
344
345                         if (result.second > 0) {
346                                 /* XXX: proper plural form support in wxWidgets? */
347                                 wxString s = result.second == 1 ? _("%d KDM written to %s") : _("%d KDMs written to %s");
348                                 message_dialog (
349                                         this,
350                                         wxString::Format (s, result.second, std_to_wx(_output->directory().string()).data())
351                                         );
352                         }
353                 } catch (dcp::NotEncryptedError& e) {
354                         error_dialog (this, _("CPL's content is not encrypted."));
355                 } catch (exception& e) {
356                         error_dialog (this, e.what ());
357                 } catch (...) {
358                         error_dialog (this, _("An unknown exception occurred."));
359                 }
360         }
361
362         void setup_sensitivity ()
363         {
364                 _screens->setup_sensitivity ();
365                 _output->setup_sensitivity ();
366                 wxArrayTreeItemIds sel;
367                 _dkdm->GetSelections (sel);
368                 _create->Enable (!_screens->screens().empty() && sel.GetCount() > 0);
369         }
370
371         void add_dkdm_clicked ()
372         {
373                 wxFileDialog* d = new wxFileDialog (this, _("Select DKDM file"));
374                 if (d->ShowModal() == wxID_OK) {
375                         shared_ptr<DKDMBase> new_dkdm (new DKDM (dcp::EncryptedKDM (dcp::file_to_string (wx_to_std (d->GetPath ()), MAX_KDM_SIZE))));
376                         shared_ptr<DKDMGroup> group = dynamic_pointer_cast<DKDMGroup> (selected_dkdm ());
377                         if (!group) {
378                                 group = Config::instance()->dkdms ();
379                         }
380                         add_dkdm_model (new_dkdm, group);
381                         add_dkdm_view (new_dkdm, group);
382                 }
383                 d->Destroy ();
384         }
385
386         void add_dkdm_folder_clicked ()
387         {
388                 NewDKDMFolderDialog* d = new NewDKDMFolderDialog (this);
389                 if (d->ShowModal() == wxID_OK) {
390                         shared_ptr<DKDMBase> new_dkdm (new DKDMGroup (wx_to_std (d->get ())));
391                         shared_ptr<DKDMGroup> parent = dynamic_pointer_cast<DKDMGroup> (selected_dkdm ());
392                         if (!parent) {
393                                 parent = Config::instance()->dkdms ();
394                         }
395                         add_dkdm_model (new_dkdm, parent);
396                         add_dkdm_view (new_dkdm, parent);
397                 }
398                 d->Destroy ();
399         }
400
401         /** @param dkdm Thing to add.
402          *  @param parent Parent group, or 0.
403          */
404         void add_dkdm_view (shared_ptr<DKDMBase> base, shared_ptr<DKDMGroup> parent)
405         {
406                 if (!parent) {
407                         /* This is the root group */
408                         _dkdm_id[_dkdm->AddRoot("root")] = base;
409                 } else {
410                         /* Add base to the view */
411                         _dkdm_id[_dkdm->AppendItem(dkdm_to_id(parent), std_to_wx(base->name()))] = base;
412                 }
413
414                 /* Add children */
415                 shared_ptr<DKDMGroup> g = dynamic_pointer_cast<DKDMGroup> (base);
416                 if (g) {
417                         BOOST_FOREACH (shared_ptr<DKDMBase> i, g->children()) {
418                                 add_dkdm_view (i, g);
419                         }
420                 }
421         }
422
423         /** @param group Group to add dkdm to */
424         void add_dkdm_model (shared_ptr<DKDMBase> dkdm, shared_ptr<DKDMGroup> group)
425         {
426                 group->add (dkdm);
427                 /* We're messing with a Config-owned object here, so tell it that something has changed.
428                    This isn't nice.
429                 */
430                 Config::instance()->changed ();
431         }
432
433         wxTreeItemId dkdm_to_id (shared_ptr<DKDMBase> dkdm)
434         {
435                 for (DKDMMap::iterator i = _dkdm_id.begin(); i != _dkdm_id.end(); ++i) {
436                         if (i->second == dkdm) {
437                                 return i->first;
438                         }
439                 }
440                 DCPOMATIC_ASSERT (false);
441         }
442
443         void remove_dkdm_clicked ()
444         {
445                 shared_ptr<DKDMBase> removed = selected_dkdm ();
446                 if (!removed) {
447                         return;
448                 }
449
450                 _dkdm->Delete (dkdm_to_id (removed));
451                 shared_ptr<DKDMGroup> dkdms = Config::instance()->dkdms ();
452                 dkdms->remove (removed);
453                 Config::instance()->changed ();
454         }
455
456         wxPreferencesEditor* _config_dialog;
457         ScreensPanel* _screens;
458         KDMTimingPanel* _timing;
459         wxTreeCtrl* _dkdm;
460         typedef std::map<wxTreeItemId, boost::shared_ptr<DKDMBase> > DKDMMap;
461         DKDMMap _dkdm_id;
462         wxButton* _add_dkdm;
463         wxButton* _add_dkdm_folder;
464         wxButton* _remove_dkdm;
465         wxButton* _create;
466         KDMOutputPanel* _output;
467         JobViewDialog* _job_view;
468 };
469
470 /** @class App
471  *  @brief The magic App class for wxWidgets.
472  */
473 class App : public wxApp
474 {
475 public:
476         App ()
477                 : wxApp ()
478                 , _frame (0)
479         {}
480
481 private:
482
483         bool OnInit ()
484         try
485         {
486                 wxInitAllImageHandlers ();
487
488                 SetAppName (_("DCP-o-matic KDM Creator"));
489
490                 if (!wxApp::OnInit()) {
491                         return false;
492                 }
493
494 #ifdef DCPOMATIC_LINUX
495                 unsetenv ("UBUNTU_MENUPROXY");
496 #endif
497
498 #ifdef __WXOSX__
499                 ProcessSerialNumber serial;
500                 GetCurrentProcess (&serial);
501                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
502 #endif
503
504                 dcpomatic_setup_path_encoding ();
505
506                 /* Enable i18n; this will create a Config object
507                    to look for a force-configured language.  This Config
508                    object will be wrong, however, because dcpomatic_setup
509                    hasn't yet been called and there aren't any filters etc.
510                    set up yet.
511                 */
512                 dcpomatic_setup_i18n ();
513
514                 /* Set things up, including filters etc.
515                    which will now be internationalised correctly.
516                 */
517                 dcpomatic_setup ();
518
519                 /* Force the configuration to be re-loaded correctly next
520                    time it is needed.
521                 */
522                 Config::drop ();
523
524                 _frame = new DOMFrame (_("DCP-o-matic KDM Creator"));
525                 SetTopWindow (_frame);
526                 _frame->Maximize ();
527                 _frame->Show ();
528
529                 signal_manager = new wxSignalManager (this);
530                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
531
532                 return true;
533         }
534         catch (exception& e)
535         {
536                 error_dialog (0, wxString::Format ("DCP-o-matic could not start: %s", e.what ()));
537                 return true;
538         }
539
540         /* An unhandled exception has occurred inside the main event loop */
541         bool OnExceptionInMainLoop ()
542         {
543                 try {
544                         throw;
545                 } catch (FileError& e) {
546                         error_dialog (
547                                 0,
548                                 wxString::Format (
549                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
550                                         std_to_wx (e.what()),
551                                         std_to_wx (e.file().string().c_str ())
552                                         )
553                                 );
554                 } catch (exception& e) {
555                         error_dialog (
556                                 0,
557                                 wxString::Format (
558                                         _("An exception occurred: %s.\n\n") + " " + REPORT_PROBLEM,
559                                         std_to_wx (e.what ())
560                                         )
561                                 );
562                 } catch (...) {
563                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
564                 }
565
566                 /* This will terminate the program */
567                 return false;
568         }
569
570         void OnUnhandledException ()
571         {
572                 error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
573         }
574
575         void idle ()
576         {
577                 signal_manager->ui_idle ();
578         }
579
580         DOMFrame* _frame;
581 };
582
583 IMPLEMENT_APP (App)