Try to clean up KDM creation code a bit.
[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 <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                                 ScreenKDM::write_files (
450                                         _film,
451                                         ScreenKDM::collect (d->screens(), _film->make_kdms (d->screens(), d->cpl(), d->from(), d->until(), d->formulation())),
452                                         d->directory()
453                                         );
454                         } else {
455                                 JobManager::instance()->add (
456                                         shared_ptr<Job> (new SendKDMEmailJob (_film, d->screens (), d->cpl (), d->from (), d->until (), d->formulation ()))
457                                         );
458                         }
459                 } catch (dcp::NotEncryptedError& e) {
460                         error_dialog (this, _("CPL's content is not encrypted."));
461                 } catch (exception& e) {
462                         error_dialog (this, e.what ());
463                 } catch (...) {
464                         error_dialog (this, _("An unknown exception occurred."));
465                 }
466
467                 d->Destroy ();
468         }
469
470         void content_scale_to_fit_width ()
471         {
472                 VideoContentList vc = _film_editor->content_panel()->selected_video ();
473                 for (VideoContentList::iterator i = vc.begin(); i != vc.end(); ++i) {
474                         (*i)->scale_and_crop_to_fit_width ();
475                 }
476         }
477
478         void content_scale_to_fit_height ()
479         {
480                 VideoContentList vc = _film_editor->content_panel()->selected_video ();
481                 for (VideoContentList::iterator i = vc.begin(); i != vc.end(); ++i) {
482                         (*i)->scale_and_crop_to_fit_height ();
483                 }
484         }
485
486         void jobs_send_dcp_to_tms ()
487         {
488                 _film->send_dcp_to_tms ();
489         }
490
491         void jobs_show_dcp ()
492         {
493 #ifdef DCPOMATIC_WINDOWS
494                 wstringstream args;
495                 args << "/select," << _film->dir (_film->dcp_name(false));
496                 ShellExecute (0, L"open", L"explorer.exe", args.str().c_str(), 0, SW_SHOWDEFAULT);
497 #endif
498
499 #ifdef DCPOMATIC_LINUX
500                 int r = system ("which nautilus");
501                 if (WEXITSTATUS (r) == 0) {
502                         r = system (string ("nautilus " + _film->directory().string()).c_str ());
503                         if (WEXITSTATUS (r)) {
504                                 error_dialog (this, _("Could not show DCP (could not run nautilus)"));
505                         }
506                 } else {
507                         int r = system ("which konqueror");
508                         if (WEXITSTATUS (r) == 0) {
509                                 r = system (string ("konqueror " + _film->directory().string()).c_str ());
510                                 if (WEXITSTATUS (r)) {
511                                         error_dialog (this, _("Could not show DCP (could not run konqueror)"));
512                                 }
513                         }
514                 }
515 #endif
516
517 #ifdef DCPOMATIC_OSX
518                 int r = system (string ("open -R " + _film->dir (_film->dcp_name (false)).string ()).c_str ());
519                 if (WEXITSTATUS (r)) {
520                         error_dialog (this, _("Could not show DCP"));
521                 }
522 #endif
523         }
524
525         void tools_video_waveform ()
526         {
527                 if (!_video_waveform_dialog) {
528                         _video_waveform_dialog = new VideoWaveformDialog (this, _film_viewer);
529                 }
530
531                 _video_waveform_dialog->Show ();
532         }
533
534         void tools_hints ()
535         {
536                 if (!_hints_dialog) {
537                         _hints_dialog = new HintsDialog (this, _film);
538                 }
539
540                 _hints_dialog->Show ();
541         }
542
543         void tools_encoding_servers ()
544         {
545                 if (!_servers_list_dialog) {
546                         _servers_list_dialog = new ServersListDialog (this);
547                 }
548
549                 _servers_list_dialog->Show ();
550         }
551
552         void tools_check_for_updates ()
553         {
554                 UpdateChecker::instance()->run ();
555         }
556
557         void help_about ()
558         {
559                 AboutDialog* d = new AboutDialog (this);
560                 d->ShowModal ();
561                 d->Destroy ();
562         }
563
564         void help_report_a_problem ()
565         {
566                 ReportProblemDialog* d = new ReportProblemDialog (this, _film);
567                 if (d->ShowModal () == wxID_OK) {
568                         d->report ();
569                 }
570                 d->Destroy ();
571         }
572
573         bool should_close ()
574         {
575                 if (!JobManager::instance()->work_to_do ()) {
576                         return true;
577                 }
578
579                 wxMessageDialog* d = new wxMessageDialog (
580                         0,
581                         _("There are unfinished jobs; are you sure you want to quit?"),
582                         _("Unfinished jobs"),
583                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
584                         );
585
586                 bool const r = d->ShowModal() == wxID_YES;
587                 d->Destroy ();
588                 return r;
589         }
590
591         void close (wxCloseEvent& ev)
592         {
593                 if (!should_close ()) {
594                         ev.Veto ();
595                         return;
596                 }
597
598                 /* We don't want to hear about any more configuration changes, since they
599                    cause the File menu to be altered, which itself will be deleted around
600                    now (without, as far as I can see, any way for us to find out).
601                 */
602                 _config_changed_connection.disconnect ();
603
604                 maybe_save_then_delete_film ();
605                 ev.Skip ();
606         }
607
608         void set_menu_sensitivity ()
609         {
610                 list<shared_ptr<Job> > jobs = JobManager::instance()->get ();
611                 list<shared_ptr<Job> >::iterator i = jobs.begin();
612                 while (i != jobs.end() && (*i)->json_name() != "transcode") {
613                         ++i;
614                 }
615                 bool const dcp_creation = (i != jobs.end ()) && !(*i)->finished ();
616                 bool const have_cpl = _film && !_film->cpls().empty ();
617                 bool const have_selected_video_content = !_film_editor->content_panel()->selected_video().empty();
618
619                 for (map<wxMenuItem*, int>::iterator j = menu_items.begin(); j != menu_items.end(); ++j) {
620
621                         bool enabled = true;
622
623                         if ((j->second & NEEDS_FILM) && !_film) {
624                                 enabled = false;
625                         }
626
627                         if ((j->second & NOT_DURING_DCP_CREATION) && dcp_creation) {
628                                 enabled = false;
629                         }
630
631                         if ((j->second & NEEDS_CPL) && !have_cpl) {
632                                 enabled = false;
633                         }
634
635                         if ((j->second & NEEDS_SELECTED_VIDEO_CONTENT) && !have_selected_video_content) {
636                                 enabled = false;
637                         }
638
639                         j->first->Enable (enabled);
640                 }
641         }
642
643         void maybe_save_then_delete_film ()
644         {
645                 if (!_film) {
646                         return;
647                 }
648
649                 if (_film->dirty ()) {
650                         FilmChangedDialog d (_film->name ());
651                         switch (d.run ()) {
652                         case wxID_NO:
653                                 break;
654                         case wxID_YES:
655                                 _film->write_metadata ();
656                                 break;
657                         }
658                 }
659
660                 _film.reset ();
661         }
662
663         void add_item (wxMenu* menu, wxString text, int id, int sens)
664         {
665                 wxMenuItem* item = menu->Append (id, text);
666                 menu_items.insert (make_pair (item, sens));
667         }
668
669         void setup_menu (wxMenuBar* m)
670         {
671                 _file_menu = new wxMenu;
672                 add_item (_file_menu, _("New...\tCtrl-N"), ID_file_new, ALWAYS);
673                 add_item (_file_menu, _("&Open...\tCtrl-O"), ID_file_open, ALWAYS);
674                 _file_menu->AppendSeparator ();
675                 add_item (_file_menu, _("&Save\tCtrl-S"), ID_file_save, NEEDS_FILM);
676
677                 _history_position = _file_menu->GetMenuItems().GetCount();
678
679 #ifndef __WXOSX__
680                 _file_menu->AppendSeparator ();
681 #endif
682
683 #ifdef __WXOSX__
684                 add_item (_file_menu, _("&Exit"), wxID_EXIT, ALWAYS);
685 #else
686                 add_item (_file_menu, _("&Quit"), wxID_EXIT, ALWAYS);
687 #endif
688
689 #ifdef __WXOSX__
690                 add_item (_file_menu, _("&Preferences...\tCtrl-P"), wxID_PREFERENCES, ALWAYS);
691 #else
692                 wxMenu* edit = new wxMenu;
693                 add_item (edit, _("&Preferences...\tCtrl-P"), wxID_PREFERENCES, ALWAYS);
694 #endif
695
696                 wxMenu* content = new wxMenu;
697                 add_item (content, _("Scale to fit &width"), ID_content_scale_to_fit_width, NEEDS_FILM | NEEDS_SELECTED_VIDEO_CONTENT);
698                 add_item (content, _("Scale to fit &height"), ID_content_scale_to_fit_height, NEEDS_FILM | NEEDS_SELECTED_VIDEO_CONTENT);
699
700                 wxMenu* jobs_menu = new wxMenu;
701                 add_item (jobs_menu, _("&Make DCP\tCtrl-M"), ID_jobs_make_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION);
702                 add_item (jobs_menu, _("Make &KDMs...\tCtrl-K"), ID_jobs_make_kdms, NEEDS_FILM);
703                 add_item (jobs_menu, _("&Send DCP to TMS"), ID_jobs_send_dcp_to_tms, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
704                 add_item (jobs_menu, _("S&how DCP"), ID_jobs_show_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
705
706                 wxMenu* tools = new wxMenu;
707                 add_item (tools, _("Video waveform..."), ID_tools_video_waveform, NEEDS_FILM);
708                 add_item (tools, _("Hints..."), ID_tools_hints, 0);
709                 add_item (tools, _("Encoding servers..."), ID_tools_encoding_servers, 0);
710                 add_item (tools, _("Check for updates"), ID_tools_check_for_updates, 0);
711                 tools->AppendSeparator ();
712                 add_item (tools, _("Restore default preferences"), ID_tools_restore_default_preferences, ALWAYS);
713
714                 wxMenu* help = new wxMenu;
715 #ifdef __WXOSX__
716                 add_item (help, _("About DCP-o-matic"), wxID_ABOUT, ALWAYS);
717 #else
718                 add_item (help, _("About"), wxID_ABOUT, ALWAYS);
719 #endif
720                 add_item (help, _("Report a problem..."), ID_help_report_a_problem, NEEDS_FILM);
721
722                 m->Append (_file_menu, _("&File"));
723 #ifndef __WXOSX__
724                 m->Append (edit, _("&Edit"));
725 #endif
726                 m->Append (content, _("&Content"));
727                 m->Append (jobs_menu, _("&Jobs"));
728                 m->Append (tools, _("&Tools"));
729                 m->Append (help, _("&Help"));
730         }
731
732         void config_changed ()
733         {
734                 for (int i = 0; i < _history_items; ++i) {
735                         delete _file_menu->Remove (ID_file_history + i);
736                 }
737
738                 if (_history_separator) {
739                         _file_menu->Remove (_history_separator);
740                 }
741                 delete _history_separator;
742                 _history_separator = 0;
743
744                 int pos = _history_position;
745
746                 vector<boost::filesystem::path> history = Config::instance()->history ();
747
748                 if (!history.empty ()) {
749                         _history_separator = _file_menu->InsertSeparator (pos++);
750                 }
751
752                 for (size_t i = 0; i < history.size(); ++i) {
753                         SafeStringStream s;
754                         if (i < 9) {
755                                 s << "&" << (i + 1) << " ";
756                         }
757                         s << history[i].string();
758                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s.str ()));
759                 }
760
761                 _history_items = history.size ();
762         }
763
764         FilmEditor* _film_editor;
765         FilmViewer* _film_viewer;
766         VideoWaveformDialog* _video_waveform_dialog;
767         HintsDialog* _hints_dialog;
768         ServersListDialog* _servers_list_dialog;
769         wxPreferencesEditor* _config_dialog;
770         wxMenu* _file_menu;
771         shared_ptr<Film> _film;
772         int _history_items;
773         int _history_position;
774         wxMenuItem* _history_separator;
775         boost::signals2::scoped_connection _config_changed_connection;
776 };
777
778 static const wxCmdLineEntryDesc command_line_description[] = {
779         { wxCMD_LINE_SWITCH, "n", "new", "create new film", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
780         { wxCMD_LINE_OPTION, "c", "content", "add content file", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
781         { wxCMD_LINE_PARAM, 0, 0, "film to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
782         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
783 };
784
785 /** @class App
786  *  @brief The magic App class for wxWidgets.
787  */
788 class App : public wxApp
789 {
790 public:
791         App ()
792                 : wxApp ()
793                 , _frame (0)
794         {}
795
796 private:
797
798         bool OnInit ()
799         try
800         {
801                 wxInitAllImageHandlers ();
802
803                 wxSplashScreen* splash = 0;
804                 try {
805                         if (!Config::have_existing ()) {
806                                 wxBitmap bitmap;
807                                 boost::filesystem::path p = shared_path () / "splash.png";
808                                 if (bitmap.LoadFile (std_to_wx (p.string ()), wxBITMAP_TYPE_PNG)) {
809                                         splash = new wxSplashScreen (bitmap, wxSPLASH_CENTRE_ON_SCREEN | wxSPLASH_NO_TIMEOUT, 0, 0, -1);
810                                         wxYield ();
811                                 }
812                         }
813                 } catch (boost::filesystem::filesystem_error& e) {
814                         /* Maybe we couldn't find the splash image; never mind */
815                 }
816
817                 SetAppName (_("DCP-o-matic"));
818
819                 if (!wxApp::OnInit()) {
820                         return false;
821                 }
822
823 #ifdef DCPOMATIC_LINUX
824                 unsetenv ("UBUNTU_MENUPROXY");
825 #endif
826
827 #ifdef __WXOSX__
828                 ProcessSerialNumber serial;
829                 GetCurrentProcess (&serial);
830                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
831 #endif
832
833                 dcpomatic_setup_path_encoding ();
834
835                 /* Enable i18n; this will create a Config object
836                    to look for a force-configured language.  This Config
837                    object will be wrong, however, because dcpomatic_setup
838                    hasn't yet been called and there aren't any filters etc.
839                    set up yet.
840                 */
841                 dcpomatic_setup_i18n ();
842
843                 /* Set things up, including filters etc.
844                    which will now be internationalised correctly.
845                 */
846                 dcpomatic_setup ();
847
848                 /* Force the configuration to be re-loaded correctly next
849                    time it is needed.
850                 */
851                 Config::drop ();
852
853                 _frame = new DOMFrame (_("DCP-o-matic"));
854                 SetTopWindow (_frame);
855                 _frame->Maximize ();
856                 if (splash) {
857                         splash->Destroy ();
858                 }
859                 _frame->Show ();
860
861                 if (!_film_to_load.empty() && boost::filesystem::is_directory (_film_to_load)) {
862                         try {
863                                 _frame->load_film (_film_to_load);
864                         } catch (exception& e) {
865                                 error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load film %1 (%2)")), _film_to_load, e.what())));
866                         }
867                 }
868
869                 if (!_film_to_create.empty ()) {
870                         _frame->new_film (_film_to_create);
871                         if (!_content_to_add.empty ()) {
872                                 _frame->film()->examine_and_add_content (content_factory (_frame->film(), _content_to_add));
873                         }
874                 }
875
876                 signal_manager = new wxSignalManager (this);
877                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
878
879                 Bind (wxEVT_TIMER, boost::bind (&App::check, this));
880                 _timer.reset (new wxTimer (this));
881                 _timer->Start (1000);
882
883                 UpdateChecker::instance()->StateChanged.connect (boost::bind (&App::update_checker_state_changed, this));
884                 if (Config::instance()->check_for_updates ()) {
885                         UpdateChecker::instance()->run ();
886                 }
887
888                 return true;
889         }
890         catch (exception& e)
891         {
892                 error_dialog (0, wxString::Format ("DCP-o-matic could not start: %s", e.what ()));
893                 return true;
894         }
895
896         void OnInitCmdLine (wxCmdLineParser& parser)
897         {
898                 parser.SetDesc (command_line_description);
899                 parser.SetSwitchChars (wxT ("-"));
900         }
901
902         bool OnCmdLineParsed (wxCmdLineParser& parser)
903         {
904                 if (parser.GetParamCount() > 0) {
905                         if (parser.Found (wxT ("new"))) {
906                                 _film_to_create = wx_to_std (parser.GetParam (0));
907                         } else {
908                                 _film_to_load = wx_to_std (parser.GetParam (0));
909                         }
910                 }
911
912                 wxString content;
913                 if (parser.Found (wxT ("content"), &content)) {
914                         _content_to_add = wx_to_std (content);
915                 }
916
917                 return true;
918         }
919
920         /* An unhandled exception has occurred inside the main event loop */
921         bool OnExceptionInMainLoop ()
922         {
923                 try {
924                         throw;
925                 } catch (FileError& e) {
926                         error_dialog (
927                                 0,
928                                 wxString::Format (
929                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
930                                         std_to_wx (e.what()),
931                                         std_to_wx (e.file().string().c_str ())
932                                         )
933                                 );
934                 } catch (exception& e) {
935                         error_dialog (
936                                 0,
937                                 wxString::Format (
938                                         _("An exception occurred: %s.\n\n") + " " + REPORT_PROBLEM,
939                                         std_to_wx (e.what ())
940                                         )
941                                 );
942                 } catch (...) {
943                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
944                 }
945
946                 /* This will terminate the program */
947                 return false;
948         }
949
950         void OnUnhandledException ()
951         {
952                 error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
953         }
954
955         void idle ()
956         {
957                 signal_manager->ui_idle ();
958         }
959
960         void check ()
961         {
962                 try {
963                         ServerFinder::instance()->rethrow ();
964                 } catch (exception& e) {
965                         error_dialog (0, std_to_wx (e.what ()));
966                 }
967         }
968
969         void update_checker_state_changed ()
970         {
971                 UpdateChecker* uc = UpdateChecker::instance ();
972                 if (uc->state() == UpdateChecker::YES && (uc->stable() || uc->test())) {
973                         UpdateDialog* dialog = new UpdateDialog (_frame, uc->stable (), uc->test ());
974                         dialog->ShowModal ();
975                         dialog->Destroy ();
976                 } else if (uc->state() == UpdateChecker::FAILED) {
977                         if (!UpdateChecker::instance()->last_emit_was_first ()) {
978                                 error_dialog (_frame, _("The DCP-o-matic download server could not be contacted."));
979                         }
980                 } else {
981                         if (!UpdateChecker::instance()->last_emit_was_first ()) {
982                                 error_dialog (_frame, _("There are no new versions of DCP-o-matic available."));
983                         }
984                 }
985         }
986
987         DOMFrame* _frame;
988         shared_ptr<wxTimer> _timer;
989         string _film_to_load;
990         string _film_to_create;
991         string _content_to_add;
992 };
993
994 IMPLEMENT_APP (App)