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