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