ac07e1785daf0cd16066be4872bbbe41992ade19
[dcpomatic.git] / src / tools / dcpomatic.cc
1 /*
2     Copyright (C) 2012-2015 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /** @file  src/tools/dcpomatic.cc
21  *  @brief The main DCP-o-matic GUI.
22  */
23
24 #include "wx/film_viewer.h"
25 #include "wx/film_editor.h"
26 #include "wx/job_manager_view.h"
27 #include "wx/config_dialog.h"
28 #include "wx/wx_util.h"
29 #include "wx/new_film_dialog.h"
30 #include "wx/wx_signal_manager.h"
31 #include "wx/about_dialog.h"
32 #include "wx/kdm_dialog.h"
33 #include "wx/servers_list_dialog.h"
34 #include "wx/hints_dialog.h"
35 #include "wx/update_dialog.h"
36 #include "wx/content_panel.h"
37 #include "wx/report_problem_dialog.h"
38 #include "wx/video_waveform_dialog.h"
39 #include "lib/film.h"
40 #include "lib/config.h"
41 #include "lib/util.h"
42 #include "lib/video_content.h"
43 #include "lib/version.h"
44 #include "lib/signal_manager.h"
45 #include "lib/log.h"
46 #include "lib/job_manager.h"
47 #include "lib/exceptions.h"
48 #include "lib/cinema.h"
49 #include "lib/kdm.h"
50 #include "lib/send_kdm_email_job.h"
51 #include "lib/server_finder.h"
52 #include "lib/update_checker.h"
53 #include "lib/cross.h"
54 #include "lib/content_factory.h"
55 #include "lib/compose.hpp"
56 #include <dcp/exceptions.h>
57 #include <wx/generic/aboutdlgg.h>
58 #include <wx/stdpaths.h>
59 #include <wx/cmdline.h>
60 #include <wx/preferences.h>
61 #include <wx/splash.h>
62 #ifdef __WXMSW__
63 #include <shellapi.h>
64 #endif
65 #ifdef __WXOSX__
66 #include <ApplicationServices/ApplicationServices.h>
67 #endif
68 #include <boost/filesystem.hpp>
69 #include <iostream>
70 #include <fstream>
71 #include <sstream>
72
73 #ifdef check
74 #undef check
75 #endif
76
77 using std::cout;
78 using std::wcout;
79 using std::string;
80 using std::vector;
81 using std::wstring;
82 using std::wstringstream;
83 using std::map;
84 using std::make_pair;
85 using std::list;
86 using std::exception;
87 using boost::shared_ptr;
88 using boost::dynamic_pointer_cast;
89
90 class FilmChangedDialog
91 {
92 public:
93         FilmChangedDialog (string name)
94         {
95                 _dialog = new wxMessageDialog (
96                         0,
97                         wxString::Format (_("Save changes to film \"%s\" before closing?"), std_to_wx (name).data()),
98                         /// TRANSLATORS: this is the heading for a dialog box, which tells the user that the current
99                         /// project (Film) has been changed since it was last saved.
100                         _("Film changed"),
101                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
102                         );
103         }
104
105         ~FilmChangedDialog ()
106         {
107                 _dialog->Destroy ();
108         }
109
110         int run ()
111         {
112                 return _dialog->ShowModal ();
113         }
114
115 private:
116         /* Not defined */
117         FilmChangedDialog (FilmChangedDialog const &);
118
119         wxMessageDialog* _dialog;
120 };
121
122 #define ALWAYS                       0x0
123 #define NEEDS_FILM                   0x1
124 #define NOT_DURING_DCP_CREATION      0x2
125 #define NEEDS_CPL                    0x4
126 #define NEEDS_SELECTED_VIDEO_CONTENT 0x8
127
128 map<wxMenuItem*, int> menu_items;
129
130 enum {
131         ID_file_new = 1,
132         ID_file_open,
133         ID_file_save,
134         ID_file_history,
135         /* Allow spare IDs after _history for the recent files list */
136         ID_content_scale_to_fit_width = 100,
137         ID_content_scale_to_fit_height,
138         ID_jobs_make_dcp,
139         ID_jobs_make_kdms,
140         ID_jobs_send_dcp_to_tms,
141         ID_jobs_show_dcp,
142         ID_tools_video_waveform,
143         ID_tools_hints,
144         ID_tools_encoding_servers,
145         ID_tools_check_for_updates,
146         ID_tools_restore_default_preferences,
147         ID_help_report_a_problem,
148         /* IDs for shortcuts (with no associated menu item) */
149         ID_add_file
150 };
151
152 class DOMFrame : public wxFrame
153 {
154 public:
155         DOMFrame (wxString const & title)
156                 : wxFrame (NULL, -1, title)
157                 , _video_waveform_dialog (0)
158                 , _hints_dialog (0)
159                 , _servers_list_dialog (0)
160                 , _config_dialog (0)
161                 , _file_menu (0)
162                 , _history_items (0)
163                 , _history_position (0)
164                 , _history_separator (0)
165         {
166 #if defined(DCPOMATIC_WINDOWS)
167                 if (Config::instance()->win32_console ()) {
168                         AllocConsole();
169
170                         HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
171                         int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
172                         FILE* hf_out = _fdopen(hCrt, "w");
173                         setvbuf(hf_out, NULL, _IONBF, 1);
174                         *stdout = *hf_out;
175
176                         HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
177                         hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
178                         FILE* hf_in = _fdopen(hCrt, "r");
179                         setvbuf(hf_in, NULL, _IONBF, 128);
180                         *stdin = *hf_in;
181
182                         cout << "DCP-o-matic is starting." << "\n";
183                 }
184 #endif
185
186                 wxMenuBar* bar = new wxMenuBar;
187                 setup_menu (bar);
188                 SetMenuBar (bar);
189
190                 _config_changed_connection = Config::instance()->Changed.connect (boost::bind (&DOMFrame::config_changed, this));
191                 config_changed ();
192
193                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::file_new, this),                ID_file_new);
194                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::file_open, this),               ID_file_open);
195                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::file_save, this),               ID_file_save);
196                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::file_history, this, _1),        ID_file_history, ID_file_history + HISTORY_SIZE);
197                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::file_exit, this),               wxID_EXIT);
198                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::edit_preferences, this),        wxID_PREFERENCES);
199                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::content_scale_to_fit_width, this), ID_content_scale_to_fit_width);
200                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::content_scale_to_fit_height, this), ID_content_scale_to_fit_height);
201                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::jobs_make_dcp, this),           ID_jobs_make_dcp);
202                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::jobs_make_kdms, this),          ID_jobs_make_kdms);
203                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::jobs_send_dcp_to_tms, this),    ID_jobs_send_dcp_to_tms);
204                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::jobs_show_dcp, this),           ID_jobs_show_dcp);
205                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::tools_video_waveform, this),    ID_tools_video_waveform);
206                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::tools_hints, this),             ID_tools_hints);
207                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::tools_encoding_servers, this),  ID_tools_encoding_servers);
208                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::tools_check_for_updates, this), ID_tools_check_for_updates);
209                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::tools_restore_default_preferences, this), ID_tools_restore_default_preferences);
210                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::help_about, this),              wxID_ABOUT);
211                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::help_report_a_problem, this),   ID_help_report_a_problem);
212
213                 Bind (wxEVT_CLOSE_WINDOW, boost::bind (&DOMFrame::close, this, _1));
214
215                 /* Use a panel as the only child of the Frame so that we avoid
216                    the dark-grey background on Windows.
217                 */
218                 wxPanel* overall_panel = new wxPanel (this, wxID_ANY);
219
220                 _film_viewer = new FilmViewer (overall_panel);
221                 _film_editor = new FilmEditor (overall_panel, _film_viewer);
222                 JobManagerView* job_manager_view = new JobManagerView (overall_panel);
223
224                 wxBoxSizer* right_sizer = new wxBoxSizer (wxVERTICAL);
225                 right_sizer->Add (_film_viewer, 2, wxEXPAND | wxALL, 6);
226                 right_sizer->Add (job_manager_view, 1, wxEXPAND | wxALL, 6);
227
228                 wxBoxSizer* main_sizer = new wxBoxSizer (wxHORIZONTAL);
229                 main_sizer->Add (_film_editor, 1, wxEXPAND | wxALL, 6);
230                 main_sizer->Add (right_sizer, 2, wxEXPAND | wxALL, 6);
231
232                 set_menu_sensitivity ();
233
234                 _film_editor->FileChanged.connect (bind (&DOMFrame::file_changed, this, _1));
235                 file_changed ("");
236
237                 JobManager::instance()->ActiveJobsChanged.connect (boost::bind (&DOMFrame::set_menu_sensitivity, this));
238
239                 overall_panel->SetSizer (main_sizer);
240
241                 wxAcceleratorEntry accel[1];
242                 accel[0].Set (wxACCEL_CTRL, static_cast<int>('A'), ID_add_file);
243                 Bind (wxEVT_MENU, boost::bind (&ContentPanel::add_file_clicked, _film_editor->content_panel()), ID_add_file);
244                 wxAcceleratorTable accel_table (1, accel);
245                 SetAcceleratorTable (accel_table);
246
247                 /* Instantly save any config changes when using the DCP-o-matic GUI */
248                 Config::instance()->Changed.connect (boost::bind (&Config::write, Config::instance ()));
249         }
250
251         void new_film (boost::filesystem::path path)
252         {
253                 shared_ptr<Film> film (new Film (path));
254                 film->write_metadata ();
255                 film->set_name (path.filename().generic_string());
256                 set_film (film);
257         }
258
259         void load_film (boost::filesystem::path file)
260         try
261         {
262                 maybe_save_then_delete_film ();
263
264                 shared_ptr<Film> film (new Film (file));
265                 list<string> const notes = film->read_metadata ();
266
267                 if (film->state_version() == 4) {
268                         error_dialog (
269                                 0,
270                                 _("This film was created with an old version of DVD-o-matic and may not load correctly "
271                                   "in this version.  Please check the film's settings carefully.")
272                                 );
273                 }
274
275                 for (list<string>::const_iterator i = notes.begin(); i != notes.end(); ++i) {
276                         error_dialog (0, std_to_wx (*i));
277                 }
278
279                 set_film (film);
280         }
281         catch (std::exception& e) {
282                 wxString p = std_to_wx (file.string ());
283                 wxCharBuffer b = p.ToUTF8 ();
284                 error_dialog (this, wxString::Format (_("Could not open film at %s (%s)"), p.data(), std_to_wx (e.what()).data()));
285         }
286
287         void set_film (shared_ptr<Film> film)
288         {
289                 _film = film;
290                 _film_viewer->set_film (_film);
291                 _film_editor->set_film (_film);
292                 set_menu_sensitivity ();
293                 Config::instance()->add_to_history (_film->directory ());
294         }
295
296         shared_ptr<Film> film () const {
297                 return _film;
298         }
299
300 private:
301
302         void file_changed (boost::filesystem::path f)
303         {
304                 string s = wx_to_std (_("DCP-o-matic"));
305                 if (!f.empty ()) {
306                         s += " - " + f.string ();
307                 }
308
309                 SetTitle (std_to_wx (s));
310         }
311
312         void file_new ()
313         {
314                 NewFilmDialog* d = new NewFilmDialog (this);
315                 int const r = d->ShowModal ();
316
317                 if (r == wxID_OK) {
318
319                         if (boost::filesystem::is_directory (d->get_path()) && !boost::filesystem::is_empty(d->get_path())) {
320                                 if (!confirm_dialog (
321                                             this,
322                                             std_to_wx (
323                                                     String::compose (wx_to_std (_("The directory %1 already exists and is not empty.  "
324                                                                                   "Are you sure you want to use it?")),
325                                                                      d->get_path().string().c_str())
326                                                     )
327                                             )) {
328                                         return;
329                                 }
330                         } else if (boost::filesystem::is_regular_file (d->get_path())) {
331                                 error_dialog (
332                                         this,
333                                         String::compose (wx_to_std (_("%1 already exists as a file, so you cannot use it for a new film.")), d->get_path().c_str())
334                                         );
335                                 return;
336                         }
337
338                         maybe_save_then_delete_film ();
339                         new_film (d->get_path ());
340                 }
341
342                 d->Destroy ();
343         }
344
345         void file_open ()
346         {
347                 wxDirDialog* c = new wxDirDialog (
348                         this,
349                         _("Select film to open"),
350                         std_to_wx (Config::instance()->default_directory_or (wx_to_std (wxStandardPaths::Get().GetDocumentsDir())).string ()),
351                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
352                         );
353
354                 int r;
355                 while (true) {
356                         r = c->ShowModal ();
357                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
358                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
359                         } else {
360                                 break;
361                         }
362                 }
363
364                 if (r == wxID_OK) {
365                         load_film (wx_to_std (c->GetPath ()));
366                 }
367
368                 c->Destroy ();
369         }
370
371         void file_save ()
372         {
373                 _film->write_metadata ();
374         }
375
376         void file_history (wxCommandEvent& event)
377         {
378                 vector<boost::filesystem::path> history = Config::instance()->history ();
379                 int n = event.GetId() - ID_file_history;
380                 if (n >= 0 && n < static_cast<int> (history.size ())) {
381                         load_film (history[n]);
382                 }
383         }
384
385         void file_exit ()
386         {
387                 /* false here allows the close handler to veto the close request */
388                 Close (false);
389         }
390
391         void edit_preferences ()
392         {
393                 if (!_config_dialog) {
394                         _config_dialog = create_config_dialog ();
395                 }
396                 _config_dialog->Show (this);
397         }
398
399         void tools_restore_default_preferences ()
400         {
401                 Config::restore_defaults ();
402         }
403
404         void jobs_make_dcp ()
405         {
406                 double required;
407                 double available;
408                 bool can_hard_link;
409
410                 if (!_film->should_be_enough_disk_space (required, available, can_hard_link)) {
411                         wxString message;
412                         if (can_hard_link) {
413                                 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);
414                         } else {
415                                 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);
416                         }
417                         if (!confirm_dialog (this, message)) {
418                                 return;
419                         }
420                 }
421
422                 try {
423                         /* It seems to make sense to auto-save metadata here, since the make DCP may last
424                            a long time, and crashes/power failures are moderately likely.
425                         */
426                         _film->write_metadata ();
427                         _film->make_dcp ();
428                 } catch (BadSettingError& e) {
429                         error_dialog (this, wxString::Format (_("Bad setting for %s (%s)"), std_to_wx(e.setting()).data(), std_to_wx(e.what()).data()));
430                 } catch (std::exception& e) {
431                         error_dialog (this, wxString::Format (_("Could not make DCP: %s"), std_to_wx(e.what()).data()));
432                 }
433         }
434
435         void jobs_make_kdms ()
436         {
437                 if (!_film) {
438                         return;
439                 }
440
441                 KDMDialog* d = new KDMDialog (this, _film);
442                 if (d->ShowModal () != wxID_OK) {
443                         d->Destroy ();
444                         return;
445                 }
446
447                 try {
448                         if (d->write_to ()) {
449                                 write_kdm_files (_film, d->screens (), d->cpl (), d->from (), d->until (), d->formulation (), d->directory ());
450                         } else {
451                                 JobManager::instance()->add (
452                                         shared_ptr<Job> (new SendKDMEmailJob (_film, d->screens (), d->cpl (), d->from (), d->until (), d->formulation ()))
453                                         );
454                         }
455                 } catch (dcp::NotEncryptedError& e) {
456                         error_dialog (this, _("CPL's content is not encrypted."));
457                 } catch (exception& e) {
458                         error_dialog (this, e.what ());
459                 } catch (...) {
460                         error_dialog (this, _("An unknown exception occurred."));
461                 }
462
463                 d->Destroy ();
464         }
465
466         void content_scale_to_fit_width ()
467         {
468                 VideoContentList vc = _film_editor->content_panel()->selected_video ();
469                 for (VideoContentList::iterator i = vc.begin(); i != vc.end(); ++i) {
470                         (*i)->scale_and_crop_to_fit_width ();
471                 }
472         }
473
474         void content_scale_to_fit_height ()
475         {
476                 VideoContentList vc = _film_editor->content_panel()->selected_video ();
477                 for (VideoContentList::iterator i = vc.begin(); i != vc.end(); ++i) {
478                         (*i)->scale_and_crop_to_fit_height ();
479                 }
480         }
481
482         void jobs_send_dcp_to_tms ()
483         {
484                 _film->send_dcp_to_tms ();
485         }
486
487         void jobs_show_dcp ()
488         {
489 #ifdef DCPOMATIC_WINDOWS
490                 wstringstream args;
491                 args << "/select," << _film->dir (_film->dcp_name(false));
492                 ShellExecute (0, L"open", L"explorer.exe", args.str().c_str(), 0, SW_SHOWDEFAULT);
493 #endif
494
495 #ifdef DCPOMATIC_LINUX
496                 int r = system ("which nautilus");
497                 if (WEXITSTATUS (r) == 0) {
498                         r = system (string ("nautilus " + _film->directory().string()).c_str ());
499                         if (WEXITSTATUS (r)) {
500                                 error_dialog (this, _("Could not show DCP (could not run nautilus)"));
501                         }
502                 } else {
503                         int r = system ("which konqueror");
504                         if (WEXITSTATUS (r) == 0) {
505                                 r = system (string ("konqueror " + _film->directory().string()).c_str ());
506                                 if (WEXITSTATUS (r)) {
507                                         error_dialog (this, _("Could not show DCP (could not run konqueror)"));
508                                 }
509                         }
510                 }
511 #endif
512
513 #ifdef DCPOMATIC_OSX
514                 int r = system (string ("open -R " + _film->dir (_film->dcp_name (false)).string ()).c_str ());
515                 if (WEXITSTATUS (r)) {
516                         error_dialog (this, _("Could not show DCP"));
517                 }
518 #endif
519         }
520
521         void tools_video_waveform ()
522         {
523                 if (!_video_waveform_dialog) {
524                         _video_waveform_dialog = new VideoWaveformDialog (this, _film_viewer);
525                 }
526
527                 _video_waveform_dialog->Show ();
528         }
529
530         void tools_hints ()
531         {
532                 if (!_hints_dialog) {
533                         _hints_dialog = new HintsDialog (this, _film);
534                 }
535
536                 _hints_dialog->Show ();
537         }
538
539         void tools_encoding_servers ()
540         {
541                 if (!_servers_list_dialog) {
542                         _servers_list_dialog = new ServersListDialog (this);
543                 }
544
545                 _servers_list_dialog->Show ();
546         }
547
548         void tools_check_for_updates ()
549         {
550                 UpdateChecker::instance()->run ();
551         }
552
553         void help_about ()
554         {
555                 AboutDialog* d = new AboutDialog (this);
556                 d->ShowModal ();
557                 d->Destroy ();
558         }
559
560         void help_report_a_problem ()
561         {
562                 ReportProblemDialog* d = new ReportProblemDialog (this, _film);
563                 if (d->ShowModal () == wxID_OK) {
564                         d->report ();
565                 }
566                 d->Destroy ();
567         }
568
569         bool should_close ()
570         {
571                 if (!JobManager::instance()->work_to_do ()) {
572                         return true;
573                 }
574
575                 wxMessageDialog* d = new wxMessageDialog (
576                         0,
577                         _("There are unfinished jobs; are you sure you want to quit?"),
578                         _("Unfinished jobs"),
579                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
580                         );
581
582                 bool const r = d->ShowModal() == wxID_YES;
583                 d->Destroy ();
584                 return r;
585         }
586
587         void close (wxCloseEvent& ev)
588         {
589                 if (!should_close ()) {
590                         ev.Veto ();
591                         return;
592                 }
593
594                 /* We don't want to hear about any more configuration changes, since they
595                    cause the File menu to be altered, which itself will be deleted around
596                    now (without, as far as I can see, any way for us to find out).
597                 */
598                 _config_changed_connection.disconnect ();
599
600                 maybe_save_then_delete_film ();
601                 ev.Skip ();
602         }
603
604         void set_menu_sensitivity ()
605         {
606                 list<shared_ptr<Job> > jobs = JobManager::instance()->get ();
607                 list<shared_ptr<Job> >::iterator i = jobs.begin();
608                 while (i != jobs.end() && (*i)->json_name() != "transcode") {
609                         ++i;
610                 }
611                 bool const dcp_creation = (i != jobs.end ()) && !(*i)->finished ();
612                 bool const have_cpl = _film && !_film->cpls().empty ();
613                 bool const have_selected_video_content = !_film_editor->content_panel()->selected_video().empty();
614
615                 for (map<wxMenuItem*, int>::iterator j = menu_items.begin(); j != menu_items.end(); ++j) {
616
617                         bool enabled = true;
618
619                         if ((j->second & NEEDS_FILM) && !_film) {
620                                 enabled = false;
621                         }
622
623                         if ((j->second & NOT_DURING_DCP_CREATION) && dcp_creation) {
624                                 enabled = false;
625                         }
626
627                         if ((j->second & NEEDS_CPL) && !have_cpl) {
628                                 enabled = false;
629                         }
630
631                         if ((j->second & NEEDS_SELECTED_VIDEO_CONTENT) && !have_selected_video_content) {
632                                 enabled = false;
633                         }
634
635                         j->first->Enable (enabled);
636                 }
637         }
638
639         void maybe_save_then_delete_film ()
640         {
641                 if (!_film) {
642                         return;
643                 }
644
645                 if (_film->dirty ()) {
646                         FilmChangedDialog d (_film->name ());
647                         switch (d.run ()) {
648                         case wxID_NO:
649                                 break;
650                         case wxID_YES:
651                                 _film->write_metadata ();
652                                 break;
653                         }
654                 }
655
656                 _film.reset ();
657         }
658
659         void add_item (wxMenu* menu, wxString text, int id, int sens)
660         {
661                 wxMenuItem* item = menu->Append (id, text);
662                 menu_items.insert (make_pair (item, sens));
663         }
664
665         void setup_menu (wxMenuBar* m)
666         {
667                 _file_menu = new wxMenu;
668                 add_item (_file_menu, _("New...\tCtrl-N"), ID_file_new, ALWAYS);
669                 add_item (_file_menu, _("&Open...\tCtrl-O"), ID_file_open, ALWAYS);
670                 _file_menu->AppendSeparator ();
671                 add_item (_file_menu, _("&Save\tCtrl-S"), ID_file_save, NEEDS_FILM);
672
673                 _history_position = _file_menu->GetMenuItems().GetCount();
674
675 #ifndef __WXOSX__
676                 _file_menu->AppendSeparator ();
677 #endif
678
679 #ifdef __WXOSX__
680                 add_item (_file_menu, _("&Exit"), wxID_EXIT, ALWAYS);
681 #else
682                 add_item (_file_menu, _("&Quit"), wxID_EXIT, ALWAYS);
683 #endif
684
685 #ifdef __WXOSX__
686                 add_item (_file_menu, _("&Preferences...\tCtrl-P"), wxID_PREFERENCES, ALWAYS);
687 #else
688                 wxMenu* edit = new wxMenu;
689                 add_item (edit, _("&Preferences...\tCtrl-P"), wxID_PREFERENCES, ALWAYS);
690 #endif
691
692                 wxMenu* content = new wxMenu;
693                 add_item (content, _("Scale to fit &width"), ID_content_scale_to_fit_width, NEEDS_FILM | NEEDS_SELECTED_VIDEO_CONTENT);
694                 add_item (content, _("Scale to fit &height"), ID_content_scale_to_fit_height, NEEDS_FILM | NEEDS_SELECTED_VIDEO_CONTENT);
695
696                 wxMenu* jobs_menu = new wxMenu;
697                 add_item (jobs_menu, _("&Make DCP\tCtrl-M"), ID_jobs_make_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION);
698                 add_item (jobs_menu, _("Make &KDMs...\tCtrl-K"), ID_jobs_make_kdms, NEEDS_FILM);
699                 add_item (jobs_menu, _("&Send DCP to TMS"), ID_jobs_send_dcp_to_tms, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
700                 add_item (jobs_menu, _("S&how DCP"), ID_jobs_show_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
701
702                 wxMenu* tools = new wxMenu;
703                 add_item (tools, _("Video waveform..."), ID_tools_video_waveform, NEEDS_FILM);
704                 add_item (tools, _("Hints..."), ID_tools_hints, 0);
705                 add_item (tools, _("Encoding servers..."), ID_tools_encoding_servers, 0);
706                 add_item (tools, _("Check for updates"), ID_tools_check_for_updates, 0);
707                 tools->AppendSeparator ();
708                 add_item (tools, _("Restore default preferences"), ID_tools_restore_default_preferences, ALWAYS);
709
710                 wxMenu* help = new wxMenu;
711 #ifdef __WXOSX__
712                 add_item (help, _("About DCP-o-matic"), wxID_ABOUT, ALWAYS);
713 #else
714                 add_item (help, _("About"), wxID_ABOUT, ALWAYS);
715 #endif
716                 add_item (help, _("Report a problem..."), ID_help_report_a_problem, NEEDS_FILM);
717
718                 m->Append (_file_menu, _("&File"));
719 #ifndef __WXOSX__
720                 m->Append (edit, _("&Edit"));
721 #endif
722                 m->Append (content, _("&Content"));
723                 m->Append (jobs_menu, _("&Jobs"));
724                 m->Append (tools, _("&Tools"));
725                 m->Append (help, _("&Help"));
726         }
727
728         void config_changed ()
729         {
730                 for (int i = 0; i < _history_items; ++i) {
731                         delete _file_menu->Remove (ID_file_history + i);
732                 }
733
734                 if (_history_separator) {
735                         _file_menu->Remove (_history_separator);
736                 }
737                 delete _history_separator;
738                 _history_separator = 0;
739
740                 int pos = _history_position;
741
742                 vector<boost::filesystem::path> history = Config::instance()->history ();
743
744                 if (!history.empty ()) {
745                         _history_separator = _file_menu->InsertSeparator (pos++);
746                 }
747
748                 for (size_t i = 0; i < history.size(); ++i) {
749                         SafeStringStream s;
750                         if (i < 9) {
751                                 s << "&" << (i + 1) << " ";
752                         }
753                         s << history[i].string();
754                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s.str ()));
755                 }
756
757                 _history_items = history.size ();
758         }
759
760         FilmEditor* _film_editor;
761         FilmViewer* _film_viewer;
762         VideoWaveformDialog* _video_waveform_dialog;
763         HintsDialog* _hints_dialog;
764         ServersListDialog* _servers_list_dialog;
765         wxPreferencesEditor* _config_dialog;
766         wxMenu* _file_menu;
767         shared_ptr<Film> _film;
768         int _history_items;
769         int _history_position;
770         wxMenuItem* _history_separator;
771         boost::signals2::scoped_connection _config_changed_connection;
772 };
773
774 static const wxCmdLineEntryDesc command_line_description[] = {
775         { wxCMD_LINE_SWITCH, "n", "new", "create new film", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
776         { wxCMD_LINE_OPTION, "c", "content", "add content file", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
777         { wxCMD_LINE_PARAM, 0, 0, "film to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
778         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
779 };
780
781 /** @class App
782  *  @brief The magic App class for wxWidgets.
783  */
784 class App : public wxApp
785 {
786 public:
787         App ()
788                 : wxApp ()
789                 , _frame (0)
790         {}
791
792 private:
793
794         bool OnInit ()
795         try
796         {
797                 wxInitAllImageHandlers ();
798
799                 wxSplashScreen* splash = 0;
800                 try {
801                         if (!Config::have_existing ()) {
802                                 wxBitmap bitmap;
803                                 boost::filesystem::path p = shared_path () / "splash.png";
804                                 if (bitmap.LoadFile (std_to_wx (p.string ()), wxBITMAP_TYPE_PNG)) {
805                                         splash = new wxSplashScreen (bitmap, wxSPLASH_CENTRE_ON_SCREEN | wxSPLASH_NO_TIMEOUT, 0, 0, -1);
806                                         wxYield ();
807                                 }
808                         }
809                 } catch (boost::filesystem::filesystem_error& e) {
810                         /* Maybe we couldn't find the splash image; never mind */
811                 }
812
813                 SetAppName (_("DCP-o-matic"));
814
815                 if (!wxApp::OnInit()) {
816                         return false;
817                 }
818
819 #ifdef DCPOMATIC_LINUX
820                 unsetenv ("UBUNTU_MENUPROXY");
821 #endif
822
823 #ifdef __WXOSX__
824                 ProcessSerialNumber serial;
825                 GetCurrentProcess (&serial);
826                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
827 #endif
828
829                 dcpomatic_setup_path_encoding ();
830
831                 /* Enable i18n; this will create a Config object
832                    to look for a force-configured language.  This Config
833                    object will be wrong, however, because dcpomatic_setup
834                    hasn't yet been called and there aren't any filters etc.
835                    set up yet.
836                 */
837                 dcpomatic_setup_i18n ();
838
839                 /* Set things up, including filters etc.
840                    which will now be internationalised correctly.
841                 */
842                 dcpomatic_setup ();
843
844                 /* Force the configuration to be re-loaded correctly next
845                    time it is needed.
846                 */
847                 Config::drop ();
848
849                 _frame = new DOMFrame (_("DCP-o-matic"));
850                 SetTopWindow (_frame);
851                 _frame->Maximize ();
852                 if (splash) {
853                         splash->Destroy ();
854                 }
855                 _frame->Show ();
856
857                 if (!_film_to_load.empty() && boost::filesystem::is_directory (_film_to_load)) {
858                         try {
859                                 _frame->load_film (_film_to_load);
860                         } catch (exception& e) {
861                                 error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load film %1 (%2)")), _film_to_load, e.what())));
862                         }
863                 }
864
865                 if (!_film_to_create.empty ()) {
866                         _frame->new_film (_film_to_create);
867                         if (!_content_to_add.empty ()) {
868                                 _frame->film()->examine_and_add_content (content_factory (_frame->film(), _content_to_add));
869                         }
870                 }
871
872                 signal_manager = new wxSignalManager (this);
873                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
874
875                 Bind (wxEVT_TIMER, boost::bind (&App::check, this));
876                 _timer.reset (new wxTimer (this));
877                 _timer->Start (1000);
878
879                 UpdateChecker::instance()->StateChanged.connect (boost::bind (&App::update_checker_state_changed, this));
880                 if (Config::instance()->check_for_updates ()) {
881                         UpdateChecker::instance()->run ();
882                 }
883
884                 return true;
885         }
886         catch (exception& e)
887         {
888                 error_dialog (0, wxString::Format ("DCP-o-matic could not start: %s", e.what ()));
889                 return true;
890         }
891
892         void OnInitCmdLine (wxCmdLineParser& parser)
893         {
894                 parser.SetDesc (command_line_description);
895                 parser.SetSwitchChars (wxT ("-"));
896         }
897
898         bool OnCmdLineParsed (wxCmdLineParser& parser)
899         {
900                 if (parser.GetParamCount() > 0) {
901                         if (parser.Found (wxT ("new"))) {
902                                 _film_to_create = wx_to_std (parser.GetParam (0));
903                         } else {
904                                 _film_to_load = wx_to_std (parser.GetParam (0));
905                         }
906                 }
907
908                 wxString content;
909                 if (parser.Found (wxT ("content"), &content)) {
910                         _content_to_add = wx_to_std (content);
911                 }
912
913                 return true;
914         }
915
916         /* An unhandled exception has occurred inside the main event loop */
917         bool OnExceptionInMainLoop ()
918         {
919                 try {
920                         throw;
921                 } catch (FileError& e) {
922                         error_dialog (
923                                 0,
924                                 wxString::Format (
925                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
926                                         std_to_wx (e.what()),
927                                         std_to_wx (e.file().string().c_str ())
928                                         )
929                                 );
930                 } catch (exception& e) {
931                         error_dialog (
932                                 0,
933                                 wxString::Format (
934                                         _("An exception occurred: %s.\n\n") + " " + REPORT_PROBLEM,
935                                         std_to_wx (e.what ())
936                                         )
937                                 );
938                 } catch (...) {
939                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
940                 }
941
942                 /* This will terminate the program */
943                 return false;
944         }
945
946         void OnUnhandledException ()
947         {
948                 error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
949         }
950
951         void idle ()
952         {
953                 signal_manager->ui_idle ();
954         }
955
956         void check ()
957         {
958                 try {
959                         ServerFinder::instance()->rethrow ();
960                 } catch (exception& e) {
961                         error_dialog (0, std_to_wx (e.what ()));
962                 }
963         }
964
965         void update_checker_state_changed ()
966         {
967                 UpdateChecker* uc = UpdateChecker::instance ();
968                 if (uc->state() == UpdateChecker::YES && (uc->stable() || uc->test())) {
969                         UpdateDialog* dialog = new UpdateDialog (_frame, uc->stable (), uc->test ());
970                         dialog->ShowModal ();
971                         dialog->Destroy ();
972                 } else if (uc->state() == UpdateChecker::FAILED) {
973                         if (!UpdateChecker::instance()->last_emit_was_first ()) {
974                                 error_dialog (_frame, _("The DCP-o-matic download server could not be contacted."));
975                         }
976                 } else {
977                         if (!UpdateChecker::instance()->last_emit_was_first ()) {
978                                 error_dialog (_frame, _("There are no new versions of DCP-o-matic available."));
979                         }
980                 }
981         }
982
983         DOMFrame* _frame;
984         shared_ptr<wxTimer> _timer;
985         string _film_to_load;
986         string _film_to_create;
987         string _content_to_add;
988 };
989
990 IMPLEMENT_APP (App)