Move ports around to allow master/server to coexist (#962).
[dcpomatic.git] / src / tools / dcpomatic.cc
1 /*
2     Copyright (C) 2012-2016 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 /** @file  src/tools/dcpomatic.cc
22  *  @brief The main DCP-o-matic GUI.
23  */
24
25 #include "wx/film_viewer.h"
26 #include "wx/film_editor.h"
27 #include "wx/job_manager_view.h"
28 #include "wx/config_dialog.h"
29 #include "wx/wx_util.h"
30 #include "wx/new_film_dialog.h"
31 #include "wx/wx_signal_manager.h"
32 #include "wx/about_dialog.h"
33 #include "wx/kdm_dialog.h"
34 #include "wx/self_dkdm_dialog.h"
35 #include "wx/servers_list_dialog.h"
36 #include "wx/hints_dialog.h"
37 #include "wx/update_dialog.h"
38 #include "wx/content_panel.h"
39 #include "wx/report_problem_dialog.h"
40 #include "wx/video_waveform_dialog.h"
41 #include "wx/save_template_dialog.h"
42 #include "wx/templates_dialog.h"
43 #include "lib/film.h"
44 #include "lib/config.h"
45 #include "lib/util.h"
46 #include "lib/video_content.h"
47 #include "lib/content.h"
48 #include "lib/version.h"
49 #include "lib/signal_manager.h"
50 #include "lib/log.h"
51 #include "lib/job_manager.h"
52 #include "lib/exceptions.h"
53 #include "lib/cinema.h"
54 #include "lib/screen_kdm.h"
55 #include "lib/send_kdm_email_job.h"
56 #include "lib/encode_server_finder.h"
57 #include "lib/update_checker.h"
58 #include "lib/cross.h"
59 #include "lib/content_factory.h"
60 #include "lib/compose.hpp"
61 #include "lib/cinema_kdms.h"
62 #include "lib/dcpomatic_socket.h"
63 #include "lib/hints.h"
64 #include "lib/dcp_content.h"
65 #include <dcp/exceptions.h>
66 #include <dcp/raw_convert.h>
67 #include <wx/generic/aboutdlgg.h>
68 #include <wx/stdpaths.h>
69 #include <wx/cmdline.h>
70 #include <wx/preferences.h>
71 #include <wx/splash.h>
72 #ifdef __WXMSW__
73 #include <shellapi.h>
74 #endif
75 #ifdef __WXOSX__
76 #include <ApplicationServices/ApplicationServices.h>
77 #endif
78 #include <boost/filesystem.hpp>
79 #include <boost/noncopyable.hpp>
80 #include <boost/foreach.hpp>
81 #include <iostream>
82 #include <fstream>
83 /* This is OK as it's only used with DCPOMATIC_WINDOWS */
84 #include <sstream>
85
86 #ifdef check
87 #undef check
88 #endif
89
90 using std::cout;
91 using std::wcout;
92 using std::string;
93 using std::vector;
94 using std::wstring;
95 using std::wstringstream;
96 using std::map;
97 using std::make_pair;
98 using std::list;
99 using std::exception;
100 using boost::shared_ptr;
101 using boost::dynamic_pointer_cast;
102 using boost::optional;
103 using dcp::raw_convert;
104
105 class FilmChangedDialog : public boost::noncopyable
106 {
107 public:
108         FilmChangedDialog (string name)
109         {
110                 _dialog = new wxMessageDialog (
111                         0,
112                         wxString::Format (_("Save changes to film \"%s\" before closing?"), std_to_wx (name).data()),
113                         /// TRANSLATORS: this is the heading for a dialog box, which tells the user that the current
114                         /// project (Film) has been changed since it was last saved.
115                         _("Film changed"),
116                         wxYES_NO | wxCANCEL | wxYES_DEFAULT | wxICON_QUESTION
117                         );
118
119                 _dialog->SetYesNoCancelLabels (
120                         _("Save film and close"), _("Close without saving film"), _("Don't close")
121                         );
122         }
123
124         ~FilmChangedDialog ()
125         {
126                 _dialog->Destroy ();
127         }
128
129         int run ()
130         {
131                 return _dialog->ShowModal ();
132         }
133
134 private:
135         wxMessageDialog* _dialog;
136 };
137
138 #define ALWAYS                       0x0
139 #define NEEDS_FILM                   0x1
140 #define NOT_DURING_DCP_CREATION      0x2
141 #define NEEDS_CPL                    0x4
142 #define NEEDS_SELECTED_VIDEO_CONTENT 0x8
143
144 map<wxMenuItem*, int> menu_items;
145
146 enum {
147         ID_file_new = 1,
148         ID_file_open,
149         ID_file_save,
150         ID_file_save_as_template,
151         ID_file_history,
152         /* Allow spare IDs after _history for the recent files list */
153         ID_content_scale_to_fit_width = 100,
154         ID_content_scale_to_fit_height,
155         ID_jobs_make_dcp,
156         ID_jobs_make_dcp_batch,
157         ID_jobs_make_kdms,
158         ID_jobs_make_self_dkdm,
159         ID_jobs_send_dcp_to_tms,
160         ID_jobs_show_dcp,
161         ID_tools_video_waveform,
162         ID_tools_hints,
163         ID_tools_encoding_servers,
164         ID_tools_manage_templates,
165         ID_tools_check_for_updates,
166         ID_tools_restore_default_preferences,
167         ID_help_report_a_problem,
168         /* IDs for shortcuts (with no associated menu item) */
169         ID_add_file,
170         ID_remove
171 };
172
173 class DOMFrame : public wxFrame
174 {
175 public:
176         DOMFrame (wxString const & title)
177                 : wxFrame (NULL, -1, title)
178                 , _video_waveform_dialog (0)
179                 , _hints_dialog (0)
180                 , _servers_list_dialog (0)
181                 , _config_dialog (0)
182                 , _kdm_dialog (0)
183                 , _templates_dialog (0)
184                 , _file_menu (0)
185                 , _history_items (0)
186                 , _history_position (0)
187                 , _history_separator (0)
188                 , _update_news_requested (false)
189         {
190 #if defined(DCPOMATIC_WINDOWS)
191                 if (Config::instance()->win32_console ()) {
192                         AllocConsole();
193
194                         HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
195                         int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
196                         FILE* hf_out = _fdopen(hCrt, "w");
197                         setvbuf(hf_out, NULL, _IONBF, 1);
198                         *stdout = *hf_out;
199
200                         HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
201                         hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
202                         FILE* hf_in = _fdopen(hCrt, "r");
203                         setvbuf(hf_in, NULL, _IONBF, 128);
204                         *stdin = *hf_in;
205
206                         cout << "DCP-o-matic is starting." << "\n";
207                 }
208 #endif
209
210                 wxMenuBar* bar = new wxMenuBar;
211                 setup_menu (bar);
212                 SetMenuBar (bar);
213
214 #ifdef DCPOMATIC_WINDOWS
215                 SetIcon (wxIcon (std_to_wx ("id")));
216 #endif
217
218                 _config_changed_connection = Config::instance()->Changed.connect (boost::bind (&DOMFrame::config_changed, this, _1));
219                 config_changed (Config::OTHER);
220
221                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_new, this),                ID_file_new);
222                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_open, this),               ID_file_open);
223                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_save, this),               ID_file_save);
224                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_save_as_template, this),   ID_file_save_as_template);
225                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_history, this, _1),        ID_file_history, ID_file_history + HISTORY_SIZE);
226                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this),               wxID_EXIT);
227                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this),        wxID_PREFERENCES);
228                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::content_scale_to_fit_width, this), ID_content_scale_to_fit_width);
229                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::content_scale_to_fit_height, this), ID_content_scale_to_fit_height);
230                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_make_dcp, this),           ID_jobs_make_dcp);
231                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_make_kdms, this),          ID_jobs_make_kdms);
232                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_make_dcp_batch, this),     ID_jobs_make_dcp_batch);
233                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_make_self_dkdm, this),     ID_jobs_make_self_dkdm);
234                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_send_dcp_to_tms, this),    ID_jobs_send_dcp_to_tms);
235                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_show_dcp, this),           ID_jobs_show_dcp);
236                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_video_waveform, this),    ID_tools_video_waveform);
237                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_hints, this),             ID_tools_hints);
238                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_encoding_servers, this),  ID_tools_encoding_servers);
239                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_manage_templates, this),  ID_tools_manage_templates);
240                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_check_for_updates, this), ID_tools_check_for_updates);
241                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_restore_default_preferences, this), ID_tools_restore_default_preferences);
242                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this),              wxID_ABOUT);
243                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this),   ID_help_report_a_problem);
244
245                 Bind (wxEVT_CLOSE_WINDOW, boost::bind (&DOMFrame::close, this, _1));
246
247                 /* Use a panel as the only child of the Frame so that we avoid
248                    the dark-grey background on Windows.
249                 */
250                 wxPanel* overall_panel = new wxPanel (this, wxID_ANY);
251
252                 _film_viewer = new FilmViewer (overall_panel);
253                 _film_editor = new FilmEditor (overall_panel, _film_viewer);
254                 JobManagerView* job_manager_view = new JobManagerView (overall_panel, false);
255
256                 wxBoxSizer* right_sizer = new wxBoxSizer (wxVERTICAL);
257                 right_sizer->Add (_film_viewer, 2, wxEXPAND | wxALL, 6);
258                 right_sizer->Add (job_manager_view, 1, wxEXPAND | wxALL, 6);
259
260                 wxBoxSizer* main_sizer = new wxBoxSizer (wxHORIZONTAL);
261                 main_sizer->Add (_film_editor, 1, wxEXPAND | wxALL, 6);
262                 main_sizer->Add (right_sizer, 2, wxEXPAND | wxALL, 6);
263
264                 set_menu_sensitivity ();
265
266                 _film_editor->FileChanged.connect (bind (&DOMFrame::file_changed, this, _1));
267                 file_changed ("");
268
269                 JobManager::instance()->ActiveJobsChanged.connect (boost::bind (&DOMFrame::set_menu_sensitivity, this));
270
271                 overall_panel->SetSizer (main_sizer);
272
273                 wxAcceleratorEntry accel[2];
274                 accel[0].Set (wxACCEL_CTRL, static_cast<int>('A'), ID_add_file);
275                 accel[1].Set (wxACCEL_NORMAL, WXK_DELETE, ID_remove);
276                 Bind (wxEVT_MENU, boost::bind (&ContentPanel::add_file_clicked, _film_editor->content_panel()), ID_add_file);
277                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::remove_clicked, this, _1), ID_remove);
278                 wxAcceleratorTable accel_table (2, accel);
279                 SetAcceleratorTable (accel_table);
280
281                 UpdateChecker::instance()->StateChanged.connect (boost::bind (&DOMFrame::update_checker_state_changed, this));
282         }
283
284         void remove_clicked (wxCommandEvent& ev)
285         {
286                 if (_film_editor->content_panel()->remove_clicked (true)) {
287                         ev.Skip ();
288                 }
289         }
290
291         void new_film (boost::filesystem::path path, optional<string> template_name)
292         {
293                 shared_ptr<Film> film (new Film (path));
294                 if (template_name) {
295                         film->use_template (template_name.get());
296                 }
297                 film->write_metadata ();
298                 film->set_name (path.filename().generic_string());
299                 set_film (film);
300         }
301
302         void load_film (boost::filesystem::path file)
303         try
304         {
305                 shared_ptr<Film> film (new Film (file));
306                 list<string> const notes = film->read_metadata ();
307
308                 if (film->state_version() == 4) {
309                         error_dialog (
310                                 0,
311                                 _("This film was created with an old version of DVD-o-matic and may not load correctly "
312                                   "in this version.  Please check the film's settings carefully.")
313                                 );
314                 }
315
316                 for (list<string>::const_iterator i = notes.begin(); i != notes.end(); ++i) {
317                         error_dialog (0, std_to_wx (*i));
318                 }
319
320                 set_film (film);
321         }
322         catch (std::exception& e) {
323                 wxString p = std_to_wx (file.string ());
324                 wxCharBuffer b = p.ToUTF8 ();
325                 error_dialog (this, wxString::Format (_("Could not open film at %s (%s)"), p.data(), std_to_wx (e.what()).data()));
326         }
327
328         void set_film (shared_ptr<Film> film)
329         {
330                 _film = film;
331                 _film_viewer->set_film (_film);
332                 _film_editor->set_film (_film);
333                 delete _video_waveform_dialog;
334                 _video_waveform_dialog = 0;
335                 set_menu_sensitivity ();
336                 if (_film->directory()) {
337                         Config::instance()->add_to_history (_film->directory().get());
338                 }
339         }
340
341         shared_ptr<Film> film () const {
342                 return _film;
343         }
344
345 private:
346
347         void file_changed (boost::filesystem::path f)
348         {
349                 string s = wx_to_std (_("DCP-o-matic"));
350                 if (!f.empty ()) {
351                         s += " - " + f.string ();
352                 }
353
354                 SetTitle (std_to_wx (s));
355         }
356
357         void file_new ()
358         {
359                 NewFilmDialog* d = new NewFilmDialog (this);
360                 int const r = d->ShowModal ();
361
362                 if (r == wxID_OK) {
363
364                         if (boost::filesystem::is_directory (d->path()) && !boost::filesystem::is_empty(d->path())) {
365                                 if (!confirm_dialog (
366                                             this,
367                                             std_to_wx (
368                                                     String::compose (wx_to_std (_("The directory %1 already exists and is not empty.  "
369                                                                                   "Are you sure you want to use it?")),
370                                                                      d->path().string().c_str())
371                                                     )
372                                             )) {
373                                         return;
374                                 }
375                         } else if (boost::filesystem::is_regular_file (d->path())) {
376                                 error_dialog (
377                                         this,
378                                         String::compose (wx_to_std (_("%1 already exists as a file, so you cannot use it for a new film.")), d->path().c_str())
379                                         );
380                                 return;
381                         }
382
383                         if (maybe_save_then_delete_film ()) {
384                                 new_film (d->path(), d->template_name());
385                         }
386                 }
387
388                 d->Destroy ();
389         }
390
391         void file_open ()
392         {
393                 wxDirDialog* c = new wxDirDialog (
394                         this,
395                         _("Select film to open"),
396                         std_to_wx (Config::instance()->default_directory_or (wx_to_std (wxStandardPaths::Get().GetDocumentsDir())).string ()),
397                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
398                         );
399
400                 int r;
401                 while (true) {
402                         r = c->ShowModal ();
403                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
404                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
405                         } else {
406                                 break;
407                         }
408                 }
409
410                 if (r == wxID_OK && maybe_save_then_delete_film()) {
411                         load_film (wx_to_std (c->GetPath ()));
412                 }
413
414                 c->Destroy ();
415         }
416
417         void file_save ()
418         {
419                 _film->write_metadata ();
420         }
421
422         void file_save_as_template ()
423         {
424                 SaveTemplateDialog* d = new SaveTemplateDialog (this);
425                 int const r = d->ShowModal ();
426                 if (r == wxID_OK) {
427                         Config::instance()->save_template (_film, d->name ());
428                 }
429                 d->Destroy ();
430         }
431
432         void file_history (wxCommandEvent& event)
433         {
434                 vector<boost::filesystem::path> history = Config::instance()->history ();
435                 int n = event.GetId() - ID_file_history;
436                 if (n >= 0 && n < static_cast<int> (history.size ()) && maybe_save_then_delete_film()) {
437                         load_film (history[n]);
438                 }
439         }
440
441         void file_exit ()
442         {
443                 /* false here allows the close handler to veto the close request */
444                 Close (false);
445         }
446
447         void edit_preferences ()
448         {
449                 if (!_config_dialog) {
450                         _config_dialog = create_config_dialog ();
451                 }
452                 _config_dialog->Show (this);
453         }
454
455         void tools_restore_default_preferences ()
456         {
457                 wxMessageDialog* d = new wxMessageDialog (
458                         0,
459                         _("Are you sure you want to restore preferences to their defaults?  This cannot be undone."),
460                         _("Restore default preferences"),
461                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
462                         );
463
464                 int const r = d->ShowModal ();
465                 d->Destroy ();
466
467                 if (r == wxID_YES) {
468                         Config::restore_defaults ();
469                 }
470         }
471
472         void jobs_make_dcp ()
473         {
474                 double required;
475                 double available;
476                 bool can_hard_link;
477
478                 if (!_film->should_be_enough_disk_space (required, available, can_hard_link)) {
479                         wxString message;
480                         if (can_hard_link) {
481                                 message = wxString::Format (_("The DCP for this film will take up about %.1f Gb, and the disk that you are using only has %.1f Gb available.  Do you want to continue anyway?"), required, available);
482                         } else {
483                                 message = wxString::Format (_("The DCP and intermediate files for this film will take up about %.1f Gb, and the disk that you are using only has %.1f Gb available.  You would need half as much space if the filesystem supported hard links, but it does not.  Do you want to continue anyway?"), required, available);
484                         }
485                         if (!confirm_dialog (this, message)) {
486                                 return;
487                         }
488                 }
489
490                 if (!get_hints(_film).empty() && Config::instance()->show_hints_before_make_dcp()) {
491                         HintsDialog* hints = new HintsDialog (this, _film, false);
492                         int const r = hints->ShowModal();
493                         hints->Destroy ();
494                         if (r == wxID_CANCEL) {
495                                 return;
496                         }
497                 }
498
499
500                 /* Remove any existing DCP if the user agrees */
501                 boost::filesystem::path const dcp_dir = _film->dir (_film->dcp_name(), false);
502                 if (boost::filesystem::exists (dcp_dir)) {
503                         if (!confirm_dialog (this, wxString::Format (_("Do you want to overwrite the existing DCP %s?"), std_to_wx(dcp_dir.string()).data()))) {
504                                 return;
505                         }
506                         boost::filesystem::remove_all (dcp_dir);
507                 }
508
509                 try {
510                         /* It seems to make sense to auto-save metadata here, since the make DCP may last
511                            a long time, and crashes/power failures are moderately likely.
512                         */
513                         _film->write_metadata ();
514                         _film->make_dcp ();
515                 } catch (BadSettingError& e) {
516                         error_dialog (this, wxString::Format (_("Bad setting for %s (%s)"), std_to_wx(e.setting()).data(), std_to_wx(e.what()).data()));
517                 } catch (std::exception& e) {
518                         error_dialog (this, wxString::Format (_("Could not make DCP: %s."), std_to_wx(e.what()).data()));
519                 }
520         }
521
522         void jobs_make_kdms ()
523         {
524                 if (!_film) {
525                         return;
526                 }
527
528                 if (_kdm_dialog) {
529                         _kdm_dialog->Destroy ();
530                         _kdm_dialog = 0;
531                 }
532
533                 _kdm_dialog = new KDMDialog (this, _film);
534                 _kdm_dialog->Show ();
535         }
536
537         void jobs_make_dcp_batch ()
538         {
539                 if (!_film) {
540                         return;
541                 }
542
543                 if (!get_hints(_film).empty() && Config::instance()->show_hints_before_make_dcp()) {
544                         HintsDialog* hints = new HintsDialog (this, _film, false);
545                         int const r = hints->ShowModal();
546                         hints->Destroy ();
547                         if (r == wxID_CANCEL) {
548                                 return;
549                         }
550                 }
551
552                 _film->write_metadata ();
553
554                 /* i = 0; try to connect via socket
555                    i = 1; try again, and then try to start the batch converter
556                    i = 2 onwards; try again.
557                 */
558                 for (int i = 0; i < 8; ++i) {
559                         try {
560                                 boost::asio::io_service io_service;
561                                 boost::asio::ip::tcp::resolver resolver (io_service);
562                                 boost::asio::ip::tcp::resolver::query query ("127.0.0.1", raw_convert<string> (BATCH_JOB_PORT));
563                                 boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve (query);
564                                 Socket socket (5);
565                                 socket.connect (*endpoint_iterator);
566                                 DCPOMATIC_ASSERT (_film->directory ());
567                                 string s = _film->directory()->string ();
568                                 socket.write (s.length() + 1);
569                                 socket.write ((uint8_t *) s.c_str(), s.length() + 1);
570                                 /* OK\0 */
571                                 uint8_t ok[3];
572                                 socket.read (ok, 3);
573                                 return;
574                         } catch (exception& e) {
575
576                         }
577
578                         if (i == 1) {
579                                 start_batch_converter (wx_to_std (wxStandardPaths::Get().GetExecutablePath()));
580                         }
581
582                         dcpomatic_sleep (1);
583                 }
584
585                 error_dialog (this, _("Could not find batch converter."));
586         }
587
588         void jobs_make_self_dkdm ()
589         {
590                 if (!_film) {
591                         return;
592                 }
593
594                 SelfDKDMDialog* d = new SelfDKDMDialog (this, _film);
595                 if (d->ShowModal () != wxID_OK) {
596                         d->Destroy ();
597                         return;
598                 }
599
600                 optional<dcp::EncryptedKDM> kdm;
601                 try {
602                         kdm = _film->make_kdm (
603                                 Config::instance()->decryption_chain()->leaf(),
604                                 vector<dcp::Certificate> (),
605                                 d->cpl (),
606                                 dcp::LocalTime ("2012-01-01T01:00:00+00:00"),
607                                 dcp::LocalTime ("2112-01-01T01:00:00+00:00"),
608                                 dcp::MODIFIED_TRANSITIONAL_1
609                                 );
610                 } catch (dcp::NotEncryptedError& e) {
611                         error_dialog (this, _("CPL's content is not encrypted."));
612                 } catch (exception& e) {
613                         error_dialog (this, e.what ());
614                 } catch (...) {
615                         error_dialog (this, _("An unknown exception occurred."));
616                 }
617
618                 if (kdm) {
619                         if (d->internal ()) {
620                                 vector<dcp::EncryptedKDM> dkdms = Config::instance()->dkdms ();
621                                 dkdms.push_back (kdm.get());
622                                 Config::instance()->set_dkdms (dkdms);
623                         } else {
624                                 boost::filesystem::path path = d->directory() / (_film->dcp_name(false) + "_DKDM.xml");
625                                 kdm->as_xml (path);
626                         }
627                 }
628
629                 d->Destroy ();
630         }
631
632         void content_scale_to_fit_width ()
633         {
634                 ContentList vc = _film_editor->content_panel()->selected_video ();
635                 for (ContentList::iterator i = vc.begin(); i != vc.end(); ++i) {
636                         (*i)->video->scale_and_crop_to_fit_width ();
637                 }
638         }
639
640         void content_scale_to_fit_height ()
641         {
642                 ContentList vc = _film_editor->content_panel()->selected_video ();
643                 for (ContentList::iterator i = vc.begin(); i != vc.end(); ++i) {
644                         (*i)->video->scale_and_crop_to_fit_height ();
645                 }
646         }
647
648         void jobs_send_dcp_to_tms ()
649         {
650                 _film->send_dcp_to_tms ();
651         }
652
653         void jobs_show_dcp ()
654         {
655                 DCPOMATIC_ASSERT (_film->directory ());
656 #ifdef DCPOMATIC_WINDOWS
657                 wstringstream args;
658                 args << "/select," << _film->dir (_film->dcp_name(false));
659                 ShellExecute (0, L"open", L"explorer.exe", args.str().c_str(), 0, SW_SHOWDEFAULT);
660 #endif
661
662 #ifdef DCPOMATIC_LINUX
663                 int r = system ("which nautilus");
664                 if (WEXITSTATUS (r) == 0) {
665                         r = system (string ("nautilus " + _film->directory()->string()).c_str ());
666                         if (WEXITSTATUS (r)) {
667                                 error_dialog (this, _("Could not show DCP (could not run nautilus)"));
668                         }
669                 } else {
670                         int r = system ("which konqueror");
671                         if (WEXITSTATUS (r) == 0) {
672                                 r = system (string ("konqueror " + _film->directory()->string()).c_str ());
673                                 if (WEXITSTATUS (r)) {
674                                         error_dialog (this, _("Could not show DCP (could not run konqueror)"));
675                                 }
676                         }
677                 }
678 #endif
679
680 #ifdef DCPOMATIC_OSX
681                 int r = system (string ("open -R " + _film->dir (_film->dcp_name (false)).string ()).c_str ());
682                 if (WEXITSTATUS (r)) {
683                         error_dialog (this, _("Could not show DCP"));
684                 }
685 #endif
686         }
687
688         void tools_video_waveform ()
689         {
690                 if (!_video_waveform_dialog) {
691                         _video_waveform_dialog = new VideoWaveformDialog (this, _film, _film_viewer);
692                 }
693
694                 _video_waveform_dialog->Show ();
695         }
696
697         void tools_hints ()
698         {
699                 if (!_hints_dialog) {
700                         _hints_dialog = new HintsDialog (this, _film, true);
701                 }
702
703                 _hints_dialog->Show ();
704         }
705
706         void tools_encoding_servers ()
707         {
708                 if (!_servers_list_dialog) {
709                         _servers_list_dialog = new ServersListDialog (this);
710                 }
711
712                 _servers_list_dialog->Show ();
713         }
714
715         void tools_manage_templates ()
716         {
717                 if (!_templates_dialog) {
718                         _templates_dialog = new TemplatesDialog (this);
719                 }
720
721                 _templates_dialog->Show ();
722         }
723
724         void tools_check_for_updates ()
725         {
726                 UpdateChecker::instance()->run ();
727                 _update_news_requested = true;
728         }
729
730         void help_about ()
731         {
732                 AboutDialog* d = new AboutDialog (this);
733                 d->ShowModal ();
734                 d->Destroy ();
735         }
736
737         void help_report_a_problem ()
738         {
739                 ReportProblemDialog* d = new ReportProblemDialog (this, _film);
740                 if (d->ShowModal () == wxID_OK) {
741                         d->report ();
742                 }
743                 d->Destroy ();
744         }
745
746         bool should_close ()
747         {
748                 if (!JobManager::instance()->work_to_do ()) {
749                         return true;
750                 }
751
752                 wxMessageDialog* d = new wxMessageDialog (
753                         0,
754                         _("There are unfinished jobs; are you sure you want to quit?"),
755                         _("Unfinished jobs"),
756                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
757                         );
758
759                 bool const r = d->ShowModal() == wxID_YES;
760                 d->Destroy ();
761                 return r;
762         }
763
764         void close (wxCloseEvent& ev)
765         {
766                 if (!should_close ()) {
767                         ev.Veto ();
768                         return;
769                 }
770
771                 if (_film && _film->dirty ()) {
772
773                         FilmChangedDialog* dialog = new FilmChangedDialog (_film->name ());
774                         int const r = dialog->run ();
775                         delete dialog;
776
777                         switch (r) {
778                         case wxID_NO:
779                                 /* Don't save and carry on to close */
780                                 break;
781                         case wxID_YES:
782                                 /* Save and carry on to close */
783                                 _film->write_metadata ();
784                                 break;
785                         case wxID_CANCEL:
786                                 /* Veto the event and stop */
787                                 ev.Veto ();
788                                 return;
789                         }
790                 }
791
792                 /* We don't want to hear about any more configuration changes, since they
793                    cause the File menu to be altered, which itself will be deleted around
794                    now (without, as far as I can see, any way for us to find out).
795                 */
796                 _config_changed_connection.disconnect ();
797
798                 ev.Skip ();
799         }
800
801         void set_menu_sensitivity ()
802         {
803                 list<shared_ptr<Job> > jobs = JobManager::instance()->get ();
804                 list<shared_ptr<Job> >::iterator i = jobs.begin();
805                 while (i != jobs.end() && (*i)->json_name() != "transcode") {
806                         ++i;
807                 }
808                 bool const dcp_creation = (i != jobs.end ()) && !(*i)->finished ();
809                 bool const have_cpl = _film && !_film->cpls().empty ();
810                 bool const have_selected_video_content = !_film_editor->content_panel()->selected_video().empty();
811
812                 for (map<wxMenuItem*, int>::iterator j = menu_items.begin(); j != menu_items.end(); ++j) {
813
814                         bool enabled = true;
815
816                         if ((j->second & NEEDS_FILM) && !_film) {
817                                 enabled = false;
818                         }
819
820                         if ((j->second & NOT_DURING_DCP_CREATION) && dcp_creation) {
821                                 enabled = false;
822                         }
823
824                         if ((j->second & NEEDS_CPL) && !have_cpl) {
825                                 enabled = false;
826                         }
827
828                         if ((j->second & NEEDS_SELECTED_VIDEO_CONTENT) && !have_selected_video_content) {
829                                 enabled = false;
830                         }
831
832                         j->first->Enable (enabled);
833                 }
834         }
835
836         /** @return true if the operation that called this method
837          *  should continue, false to abort it.
838          */
839         bool maybe_save_then_delete_film ()
840         {
841                 if (!_film) {
842                         return true;
843                 }
844
845                 if (_film->dirty ()) {
846                         FilmChangedDialog d (_film->name ());
847                         switch (d.run ()) {
848                         case wxID_NO:
849                                 break;
850                         case wxID_YES:
851                                 _film->write_metadata ();
852                                 break;
853                         case wxID_CANCEL:
854                                 return false;
855                         }
856                 }
857
858                 _film.reset ();
859                 return true;
860         }
861
862         void add_item (wxMenu* menu, wxString text, int id, int sens)
863         {
864                 wxMenuItem* item = menu->Append (id, text);
865                 menu_items.insert (make_pair (item, sens));
866         }
867
868         void setup_menu (wxMenuBar* m)
869         {
870                 _file_menu = new wxMenu;
871                 add_item (_file_menu, _("New...\tCtrl-N"), ID_file_new, ALWAYS);
872                 add_item (_file_menu, _("&Open...\tCtrl-O"), ID_file_open, ALWAYS);
873                 _file_menu->AppendSeparator ();
874                 add_item (_file_menu, _("&Save\tCtrl-S"), ID_file_save, NEEDS_FILM);
875                 _file_menu->AppendSeparator ();
876                 add_item (_file_menu, _("Save as &template..."), ID_file_save_as_template, NEEDS_FILM);
877
878                 _history_position = _file_menu->GetMenuItems().GetCount();
879
880 #ifndef __WXOSX__
881                 _file_menu->AppendSeparator ();
882 #endif
883
884 #ifdef __WXOSX__
885                 add_item (_file_menu, _("&Exit"), wxID_EXIT, ALWAYS);
886 #else
887                 add_item (_file_menu, _("&Quit"), wxID_EXIT, ALWAYS);
888 #endif
889
890 #ifdef __WXOSX__
891                 add_item (_file_menu, _("&Preferences...\tCtrl-P"), wxID_PREFERENCES, ALWAYS);
892 #else
893                 wxMenu* edit = new wxMenu;
894                 add_item (edit, _("&Preferences...\tCtrl-P"), wxID_PREFERENCES, ALWAYS);
895 #endif
896
897                 wxMenu* content = new wxMenu;
898                 add_item (content, _("Scale to fit &width"), ID_content_scale_to_fit_width, NEEDS_FILM | NEEDS_SELECTED_VIDEO_CONTENT);
899                 add_item (content, _("Scale to fit &height"), ID_content_scale_to_fit_height, NEEDS_FILM | NEEDS_SELECTED_VIDEO_CONTENT);
900
901                 wxMenu* jobs_menu = new wxMenu;
902                 add_item (jobs_menu, _("&Make DCP\tCtrl-M"), ID_jobs_make_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION);
903                 add_item (jobs_menu, _("Make DCP in &batch converter\tCtrl-B"), ID_jobs_make_dcp_batch, NEEDS_FILM | NOT_DURING_DCP_CREATION);
904                 add_item (jobs_menu, _("Make &KDMs...\tCtrl-K"), ID_jobs_make_kdms, NEEDS_FILM);
905                 add_item (jobs_menu, _("Make DKDM for DCP-o-matic..."), ID_jobs_make_self_dkdm, NEEDS_FILM);
906                 add_item (jobs_menu, _("&Send DCP to TMS"), ID_jobs_send_dcp_to_tms, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
907                 add_item (jobs_menu, _("S&how DCP"), ID_jobs_show_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
908
909                 wxMenu* tools = new wxMenu;
910                 add_item (tools, _("Video waveform..."), ID_tools_video_waveform, NEEDS_FILM);
911                 add_item (tools, _("Hints..."), ID_tools_hints, 0);
912                 add_item (tools, _("Encoding servers..."), ID_tools_encoding_servers, 0);
913                 add_item (tools, _("Manage templates..."), ID_tools_manage_templates, 0);
914                 add_item (tools, _("Check for updates"), ID_tools_check_for_updates, 0);
915                 tools->AppendSeparator ();
916                 add_item (tools, _("Restore default preferences"), ID_tools_restore_default_preferences, ALWAYS);
917
918                 wxMenu* help = new wxMenu;
919 #ifdef __WXOSX__
920                 add_item (help, _("About DCP-o-matic"), wxID_ABOUT, ALWAYS);
921 #else
922                 add_item (help, _("About"), wxID_ABOUT, ALWAYS);
923 #endif
924                 add_item (help, _("Report a problem..."), ID_help_report_a_problem, NEEDS_FILM);
925
926                 m->Append (_file_menu, _("&File"));
927 #ifndef __WXOSX__
928                 m->Append (edit, _("&Edit"));
929 #endif
930                 m->Append (content, _("&Content"));
931                 m->Append (jobs_menu, _("&Jobs"));
932                 m->Append (tools, _("&Tools"));
933                 m->Append (help, _("&Help"));
934         }
935
936         void config_changed (Config::Property what)
937         {
938                 /* Instantly save any config changes when using the DCP-o-matic GUI */
939                 if (what == Config::CINEMAS) {
940                         try {
941                                 Config::instance()->write_cinemas();
942                         } catch (exception& e) {
943                                 error_dialog (
944                                         this,
945                                         wxString::Format (
946                                                 _("Could not write to cinemas file at %s.  Your changes have not been saved."),
947                                                 std_to_wx (Config::instance()->cinemas_file().string()).data()
948                                                 )
949                                         );
950                         }
951                 } else {
952                         try {
953                                 Config::instance()->write_config();
954                         } catch (exception& e) {
955                                 error_dialog (
956                                         this,
957                                         wxString::Format (
958                                                 _("Could not write to config file at %s.  Your changes have not been saved."),
959                                                 std_to_wx (Config::instance()->cinemas_file().string()).data()
960                                                 )
961                                         );
962                         }
963                 }
964
965                 for (int i = 0; i < _history_items; ++i) {
966                         delete _file_menu->Remove (ID_file_history + i);
967                 }
968
969                 if (_history_separator) {
970                         _file_menu->Remove (_history_separator);
971                 }
972                 delete _history_separator;
973                 _history_separator = 0;
974
975                 int pos = _history_position;
976
977                 vector<boost::filesystem::path> history = Config::instance()->history ();
978
979                 if (!history.empty ()) {
980                         _history_separator = _file_menu->InsertSeparator (pos++);
981                 }
982
983                 for (size_t i = 0; i < history.size(); ++i) {
984                         string s;
985                         if (i < 9) {
986                                 s = String::compose ("&%1 %2", i + 1, history[i].string());
987                         } else {
988                                 s = history[i].string();
989                         }
990                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s));
991                 }
992
993                 _history_items = history.size ();
994         }
995
996         void update_checker_state_changed ()
997         {
998                 UpdateChecker* uc = UpdateChecker::instance ();
999
1000                 bool const announce =
1001                         _update_news_requested ||
1002                         (uc->stable() && Config::instance()->check_for_updates()) ||
1003                         (uc->test() && Config::instance()->check_for_updates() && Config::instance()->check_for_test_updates());
1004
1005                 _update_news_requested = false;
1006
1007                 if (!announce) {
1008                         return;
1009                 }
1010
1011                 if (uc->state() == UpdateChecker::YES) {
1012                         UpdateDialog* dialog = new UpdateDialog (this, uc->stable (), uc->test ());
1013                         dialog->ShowModal ();
1014                         dialog->Destroy ();
1015                 } else if (uc->state() == UpdateChecker::FAILED) {
1016                         error_dialog (this, _("The DCP-o-matic download server could not be contacted."));
1017                 } else {
1018                         error_dialog (this, _("There are no new versions of DCP-o-matic available."));
1019                 }
1020
1021                 _update_news_requested = false;
1022         }
1023
1024         FilmEditor* _film_editor;
1025         FilmViewer* _film_viewer;
1026         VideoWaveformDialog* _video_waveform_dialog;
1027         HintsDialog* _hints_dialog;
1028         ServersListDialog* _servers_list_dialog;
1029         wxPreferencesEditor* _config_dialog;
1030         KDMDialog* _kdm_dialog;
1031         TemplatesDialog* _templates_dialog;
1032         wxMenu* _file_menu;
1033         shared_ptr<Film> _film;
1034         int _history_items;
1035         int _history_position;
1036         wxMenuItem* _history_separator;
1037         boost::signals2::scoped_connection _config_changed_connection;
1038         bool _update_news_requested;
1039 };
1040
1041 static const wxCmdLineEntryDesc command_line_description[] = {
1042         { wxCMD_LINE_SWITCH, "n", "new", "create new film", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
1043         { wxCMD_LINE_OPTION, "c", "content", "add content file / directory", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1044         { wxCMD_LINE_OPTION, "d", "dcp", "add content DCP", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1045         { wxCMD_LINE_PARAM, 0, 0, "film to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1046         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
1047 };
1048
1049 /** @class App
1050  *  @brief The magic App class for wxWidgets.
1051  */
1052 class App : public wxApp
1053 {
1054 public:
1055         App ()
1056                 : wxApp ()
1057                 , _frame (0)
1058         {}
1059
1060 private:
1061
1062         bool OnInit ()
1063         try
1064         {
1065                 wxInitAllImageHandlers ();
1066
1067                 Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
1068
1069                 wxSplashScreen* splash = 0;
1070                 try {
1071                         if (!Config::have_existing ("config.xml")) {
1072                                 wxBitmap bitmap;
1073                                 boost::filesystem::path p = shared_path () / "splash.png";
1074                                 if (bitmap.LoadFile (std_to_wx (p.string ()), wxBITMAP_TYPE_PNG)) {
1075                                         splash = new wxSplashScreen (bitmap, wxSPLASH_CENTRE_ON_SCREEN | wxSPLASH_NO_TIMEOUT, 0, 0, -1);
1076                                         wxYield ();
1077                                 }
1078                         }
1079                 } catch (boost::filesystem::filesystem_error& e) {
1080                         /* Maybe we couldn't find the splash image; never mind */
1081                 }
1082
1083                 SetAppName (_("DCP-o-matic"));
1084
1085                 if (!wxApp::OnInit()) {
1086                         return false;
1087                 }
1088
1089 #ifdef DCPOMATIC_LINUX
1090                 unsetenv ("UBUNTU_MENUPROXY");
1091 #endif
1092
1093 #ifdef __WXOSX__
1094                 ProcessSerialNumber serial;
1095                 GetCurrentProcess (&serial);
1096                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
1097 #endif
1098
1099                 dcpomatic_setup_path_encoding ();
1100
1101                 /* Enable i18n; this will create a Config object
1102                    to look for a force-configured language.  This Config
1103                    object will be wrong, however, because dcpomatic_setup
1104                    hasn't yet been called and there aren't any filters etc.
1105                    set up yet.
1106                 */
1107                 dcpomatic_setup_i18n ();
1108
1109                 /* Set things up, including filters etc.
1110                    which will now be internationalised correctly.
1111                 */
1112                 dcpomatic_setup ();
1113
1114                 /* Force the configuration to be re-loaded correctly next
1115                    time it is needed.
1116                 */
1117                 Config::drop ();
1118
1119                 _frame = new DOMFrame (_("DCP-o-matic"));
1120                 SetTopWindow (_frame);
1121                 _frame->Maximize ();
1122                 if (splash) {
1123                         splash->Destroy ();
1124                 }
1125                 _frame->Show ();
1126
1127                 if (!_film_to_load.empty() && boost::filesystem::is_directory (_film_to_load)) {
1128                         try {
1129                                 _frame->load_film (_film_to_load);
1130                         } catch (exception& e) {
1131                                 error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load film %1 (%2)")), _film_to_load, e.what())));
1132                         }
1133                 }
1134
1135                 if (!_film_to_create.empty ()) {
1136                         _frame->new_film (_film_to_create, optional<string> ());
1137                         if (!_content_to_add.empty ()) {
1138                                 BOOST_FOREACH (shared_ptr<Content> i, content_factory (_frame->film(), _content_to_add)) {
1139                                         _frame->film()->examine_and_add_content (i);
1140                                 }
1141                         }
1142                         if (!_dcp_to_add.empty ()) {
1143                                 _frame->film()->examine_and_add_content (shared_ptr<DCPContent> (new DCPContent (_frame->film(), _dcp_to_add)));
1144                         }
1145                 }
1146
1147                 signal_manager = new wxSignalManager (this);
1148                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
1149
1150                 Bind (wxEVT_TIMER, boost::bind (&App::check, this));
1151                 _timer.reset (new wxTimer (this));
1152                 _timer->Start (1000);
1153
1154                 if (Config::instance()->check_for_updates ()) {
1155                         UpdateChecker::instance()->run ();
1156                 }
1157
1158                 return true;
1159         }
1160         catch (exception& e)
1161         {
1162                 error_dialog (0, wxString::Format ("DCP-o-matic could not start: %s", e.what ()));
1163                 return true;
1164         }
1165
1166         void OnInitCmdLine (wxCmdLineParser& parser)
1167         {
1168                 parser.SetDesc (command_line_description);
1169                 parser.SetSwitchChars (wxT ("-"));
1170         }
1171
1172         bool OnCmdLineParsed (wxCmdLineParser& parser)
1173         {
1174                 if (parser.GetParamCount() > 0) {
1175                         if (parser.Found (wxT ("new"))) {
1176                                 _film_to_create = wx_to_std (parser.GetParam (0));
1177                         } else {
1178                                 _film_to_load = wx_to_std (parser.GetParam (0));
1179                         }
1180                 }
1181
1182                 wxString content;
1183                 if (parser.Found (wxT ("content"), &content)) {
1184                         _content_to_add = wx_to_std (content);
1185                 }
1186
1187                 wxString dcp;
1188                 if (parser.Found (wxT ("dcp"), &dcp)) {
1189                         _dcp_to_add = wx_to_std (dcp);
1190                 }
1191
1192                 return true;
1193         }
1194
1195         void report_exception ()
1196         {
1197                 try {
1198                         throw;
1199                 } catch (FileError& e) {
1200                         error_dialog (
1201                                 0,
1202                                 wxString::Format (
1203                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
1204                                         std_to_wx (e.what()),
1205                                         std_to_wx (e.file().string().c_str ())
1206                                         )
1207                                 );
1208                 } catch (exception& e) {
1209                         error_dialog (
1210                                 0,
1211                                 wxString::Format (
1212                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
1213                                         std_to_wx (e.what ())
1214                                         )
1215                                 );
1216                 } catch (...) {
1217                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
1218                 }
1219         }
1220
1221         /* An unhandled exception has occurred inside the main event loop */
1222         bool OnExceptionInMainLoop ()
1223         {
1224                 report_exception ();
1225                 /* This will terminate the program */
1226                 return false;
1227         }
1228
1229         void OnUnhandledException ()
1230         {
1231                 report_exception ();
1232         }
1233
1234         void idle ()
1235         {
1236                 signal_manager->ui_idle ();
1237         }
1238
1239         void check ()
1240         {
1241                 try {
1242                         EncodeServerFinder::instance()->rethrow ();
1243                 } catch (exception& e) {
1244                         error_dialog (0, std_to_wx (e.what ()));
1245                 }
1246         }
1247
1248         void config_failed_to_load ()
1249         {
1250                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
1251         }
1252
1253         DOMFrame* _frame;
1254         shared_ptr<wxTimer> _timer;
1255         string _film_to_load;
1256         string _film_to_create;
1257         string _content_to_add;
1258         string _dcp_to_add;
1259 };
1260
1261 IMPLEMENT_APP (App)