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