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