904e39fdaf3a048a8a2a60d67b9322690364c962
[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 #include "lib/film.h"
21 #include "lib/config.h"
22 #include "lib/util.h"
23 #include "lib/version.h"
24 #include "lib/signal_manager.h"
25 #include "lib/log.h"
26 #include "lib/job_manager.h"
27 #include "lib/transcode_job.h"
28 #include "lib/exceptions.h"
29 #include "lib/cinema.h"
30 #include "lib/kdm.h"
31 #include "lib/send_kdm_email_job.h"
32 #include "lib/server_finder.h"
33 #include "lib/update.h"
34 #include "lib/content_factory.h"
35 #include "wx/film_viewer.h"
36 #include "wx/film_editor.h"
37 #include "wx/job_manager_view.h"
38 #include "wx/config_dialog.h"
39 #include "wx/wx_util.h"
40 #include "wx/new_film_dialog.h"
41 #include "wx/properties_dialog.h"
42 #include "wx/wx_signal_manager.h"
43 #include "wx/about_dialog.h"
44 #include "wx/kdm_dialog.h"
45 #include "wx/servers_list_dialog.h"
46 #include "wx/hints_dialog.h"
47 #include "wx/update_dialog.h"
48 #include "wx/content_panel.h"
49 #include "wx/report_problem_dialog.h"
50 #include <dcp/exceptions.h>
51 #include <wx/generic/aboutdlgg.h>
52 #include <wx/stdpaths.h>
53 #include <wx/cmdline.h>
54 #include <wx/preferences.h>
55 #ifdef __WXMSW__
56 #include <shellapi.h>
57 #endif
58 #ifdef __WXOSX__
59 #include <ApplicationServices/ApplicationServices.h>
60 #endif
61 #include <boost/filesystem.hpp>
62 #include <iostream>
63 #include <fstream>
64 #include <sstream>
65
66 #ifdef check
67 #undef check
68 #endif
69
70 using std::cout;
71 using std::wcout;
72 using std::string;
73 using std::vector;
74 using std::wstring;
75 using std::wstringstream;
76 using std::map;
77 using std::make_pair;
78 using std::list;
79 using std::exception;
80 using boost::shared_ptr;
81 using boost::dynamic_pointer_cast;
82
83 class FilmChangedDialog
84 {
85 public:
86         FilmChangedDialog (string name)
87         {
88                 _dialog = new wxMessageDialog (
89                         0,
90                         wxString::Format (_("Save changes to film \"%s\" before closing?"), std_to_wx (name).data()),
91                         /* TRANSLATORS: this is the heading for a dialog box, which tells the user that the current
92                            project (Film) has been changed since it was last saved.
93                         */
94                         _("Film changed"),
95                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
96                         );
97         }
98
99         ~FilmChangedDialog ()
100         {
101                 _dialog->Destroy ();
102         }
103
104         int run ()
105         {
106                 return _dialog->ShowModal ();
107         }
108
109 private:
110         /* Not defined */
111         FilmChangedDialog (FilmChangedDialog const &);
112         
113         wxMessageDialog* _dialog;
114 };
115
116 #define ALWAYS                       0x0
117 #define NEEDS_FILM                   0x1
118 #define NOT_DURING_DCP_CREATION      0x2
119 #define NEEDS_CPL                    0x4
120 #define NEEDS_SELECTED_VIDEO_CONTENT 0x8
121
122 map<wxMenuItem*, int> menu_items;
123         
124 enum {
125         ID_file_new = 1,
126         ID_file_open,
127         ID_file_save,
128         ID_file_properties,
129         ID_file_history,
130         /* Allow spare IDs after _history for the recent files list */
131         ID_content_scale_to_fit_width = 100,
132         ID_content_scale_to_fit_height,
133         ID_jobs_make_dcp,
134         ID_jobs_make_kdms,
135         ID_jobs_send_dcp_to_tms,
136         ID_jobs_show_dcp,
137         ID_tools_hints,
138         ID_tools_encoding_servers,
139         ID_tools_check_for_updates,
140         ID_tools_restore_default_preferences,
141         ID_help_report_a_problem,
142         /* IDs for shortcuts (with no associated menu item) */
143         ID_add_file
144 };
145
146 class Frame : public wxFrame
147 {
148 public:
149         Frame (wxString const & title)
150                 : wxFrame (NULL, -1, title)
151                 , _hints_dialog (0)
152                 , _servers_list_dialog (0)
153                 , _config_dialog (0)
154                 , _file_menu (0)
155                 , _history_items (0)
156                 , _history_position (0)
157                 , _history_separator (0)
158         {
159 #if defined(DCPOMATIC_WINDOWS)
160                 if (Config::instance()->win32_console ()) {
161                         AllocConsole();
162                         
163                         HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
164                         int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
165                         FILE* hf_out = _fdopen(hCrt, "w");
166                         setvbuf(hf_out, NULL, _IONBF, 1);
167                         *stdout = *hf_out;
168                         
169                         HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
170                         hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
171                         FILE* hf_in = _fdopen(hCrt, "r");
172                         setvbuf(hf_in, NULL, _IONBF, 128);
173                         *stdin = *hf_in;
174
175                         cout << "DCP-o-matic is starting." << "\n";
176                 }
177 #endif
178
179                 wxMenuBar* bar = new wxMenuBar;
180                 setup_menu (bar);
181                 SetMenuBar (bar);
182
183                 _config_changed_connection = Config::instance()->Changed.connect (boost::bind (&Frame::config_changed, this));
184                 config_changed ();
185
186                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::file_new, this),                ID_file_new);
187                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::file_open, this),               ID_file_open);
188                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::file_save, this),               ID_file_save);
189                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::file_properties, this),         ID_file_properties);
190                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::file_history, this, _1),        ID_file_history, ID_file_history + HISTORY_SIZE);
191                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::file_exit, this),               wxID_EXIT);
192                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::edit_preferences, this),        wxID_PREFERENCES);
193                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::content_scale_to_fit_width, this), ID_content_scale_to_fit_width);
194                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::content_scale_to_fit_height, this), ID_content_scale_to_fit_height);
195                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::jobs_make_dcp, this),           ID_jobs_make_dcp);
196                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::jobs_make_kdms, this),          ID_jobs_make_kdms);
197                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::jobs_send_dcp_to_tms, this),    ID_jobs_send_dcp_to_tms);
198                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::jobs_show_dcp, this),           ID_jobs_show_dcp);
199                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::tools_hints, this),             ID_tools_hints);
200                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::tools_encoding_servers, this),  ID_tools_encoding_servers);
201                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::tools_check_for_updates, this), ID_tools_check_for_updates);
202                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::tools_restore_default_preferences, this), ID_tools_restore_default_preferences);
203                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::help_about, this),              wxID_ABOUT);
204                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::help_report_a_problem, this),   ID_help_report_a_problem);
205
206                 Bind (wxEVT_CLOSE_WINDOW, boost::bind (&Frame::close, this, _1));
207
208                 /* Use a panel as the only child of the Frame so that we avoid
209                    the dark-grey background on Windows.
210                 */
211                 wxPanel* overall_panel = new wxPanel (this, wxID_ANY);
212
213                 _film_editor = new FilmEditor (overall_panel);
214                 _film_viewer = new FilmViewer (overall_panel);
215                 JobManagerView* job_manager_view = new JobManagerView (overall_panel);
216
217                 wxBoxSizer* right_sizer = new wxBoxSizer (wxVERTICAL);
218                 right_sizer->Add (_film_viewer, 2, wxEXPAND | wxALL, 6);
219                 right_sizer->Add (job_manager_view, 1, wxEXPAND | wxALL, 6);
220
221                 wxBoxSizer* main_sizer = new wxBoxSizer (wxHORIZONTAL);
222                 main_sizer->Add (_film_editor, 1, wxEXPAND | wxALL, 6);
223                 main_sizer->Add (right_sizer, 2, wxEXPAND | wxALL, 6);
224
225                 set_menu_sensitivity ();
226
227                 _film_editor->FileChanged.connect (bind (&Frame::file_changed, this, _1));
228                 file_changed ("");
229
230                 JobManager::instance()->ActiveJobsChanged.connect (boost::bind (&Frame::set_menu_sensitivity, this));
231
232                 overall_panel->SetSizer (main_sizer);
233
234                 wxAcceleratorEntry accel[1];
235                 accel[0].Set (wxACCEL_CTRL, static_cast<int>('A'), ID_add_file);
236                 Bind (wxEVT_MENU, boost::bind (&ContentPanel::add_file_clicked, _film_editor->content_panel()), ID_add_file);
237                 wxAcceleratorTable accel_table (1, accel);
238                 SetAcceleratorTable (accel_table);
239
240                 /* Instantly save any config changes when using the DCP-o-matic GUI */
241                 Config::instance()->Changed.connect (boost::bind (&Config::write, Config::instance ()));
242         }
243
244         void new_film (boost::filesystem::path path)
245         {
246                 shared_ptr<Film> film (new Film (path));
247                 film->write_metadata ();
248                 film->set_name (path.filename().generic_string());
249                 set_film (film);
250         }
251
252         void load_film (boost::filesystem::path file)
253         try
254         {
255                 maybe_save_then_delete_film ();
256                 
257                 shared_ptr<Film> film (new Film (file));
258                 list<string> const notes = film->read_metadata ();
259
260                 if (film->state_version() == 4) {
261                         error_dialog (
262                                 0,
263                                 _("This film was created with an old version of DVD-o-matic and may not load correctly "
264                                   "in this version.  Please check the film's settings carefully.")
265                                 );
266                 }
267                 
268                 for (list<string>::const_iterator i = notes.begin(); i != notes.end(); ++i) {
269                         error_dialog (0, std_to_wx (*i));
270                 }
271                 
272                 set_film (film);
273         }
274         catch (std::exception& e) {
275                 wxString p = std_to_wx (file.string ());
276                 wxCharBuffer b = p.ToUTF8 ();
277                 error_dialog (this, wxString::Format (_("Could not open film at %s (%s)"), p.data(), std_to_wx (e.what()).data()));
278         }
279
280         void set_film (shared_ptr<Film> film)
281         {
282                 _film = film;
283                 _film_viewer->set_film (_film);
284                 _film_editor->set_film (_film);
285                 set_menu_sensitivity ();
286                 Config::instance()->add_to_history (_film->directory ());
287         }
288
289         shared_ptr<Film> film () const {
290                 return _film;
291         }
292         
293 private:
294
295         void file_changed (boost::filesystem::path f)
296         {
297                 string s = wx_to_std (_("DCP-o-matic"));
298                 if (!f.empty ()) {
299                         s += " - " + f.string ();
300                 }
301                 
302                 SetTitle (std_to_wx (s));
303         }
304         
305         void file_new ()
306         {
307                 NewFilmDialog* d = new NewFilmDialog (this);
308                 int const r = d->ShowModal ();
309                 
310                 if (r == wxID_OK) {
311
312                         if (boost::filesystem::is_directory (d->get_path()) && !boost::filesystem::is_empty(d->get_path())) {
313                                 if (!confirm_dialog (
314                                             this,
315                                             std_to_wx (
316                                                     String::compose (wx_to_std (_("The directory %1 already exists and is not empty.  "
317                                                                                   "Are you sure you want to use it?")),
318                                                                      d->get_path().string().c_str())
319                                                     )
320                                             )) {
321                                         return;
322                                 }
323                         } else if (boost::filesystem::is_regular_file (d->get_path())) {
324                                 error_dialog (
325                                         this,
326                                         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())
327                                         );
328                                 return;
329                         }
330                         
331                         maybe_save_then_delete_film ();
332                         new_film (d->get_path ());
333                 }
334                 
335                 d->Destroy ();
336         }
337
338         void file_open ()
339         {
340                 wxDirDialog* c = new wxDirDialog (
341                         this,
342                         _("Select film to open"),
343                         std_to_wx (Config::instance()->default_directory_or (wx_to_std (wxStandardPaths::Get().GetDocumentsDir())).string ()),
344                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
345                         );
346                 
347                 int r;
348                 while (true) {
349                         r = c->ShowModal ();
350                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
351                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
352                         } else {
353                                 break;
354                         }
355                 }
356                         
357                 if (r == wxID_OK) {
358                         load_film (wx_to_std (c->GetPath ()));
359                 }
360
361                 c->Destroy ();
362         }
363
364         void file_save ()
365         {
366                 _film->write_metadata ();
367         }
368
369         void file_properties ()
370         {
371                 PropertiesDialog* d = new PropertiesDialog (this, _film);
372                 d->ShowModal ();
373                 d->Destroy ();
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_hints ()
522         {
523                 if (!_hints_dialog) {
524                         _hints_dialog = new HintsDialog (this, _film);
525                 }
526
527                 _hints_dialog->Show ();
528         }
529
530         void tools_encoding_servers ()
531         {
532                 if (!_servers_list_dialog) {
533                         _servers_list_dialog = new ServersListDialog (this);
534                 }
535
536                 _servers_list_dialog->Show ();
537         }
538
539         void tools_check_for_updates ()
540         {
541                 UpdateChecker::instance()->run ();
542         }
543
544         void help_about ()
545         {
546                 AboutDialog* d = new AboutDialog (this);
547                 d->ShowModal ();
548                 d->Destroy ();
549         }
550
551         void help_report_a_problem ()
552         {
553                 ReportProblemDialog* d = new ReportProblemDialog (this, _film);
554                 if (d->ShowModal () == wxID_OK) {
555                         d->report ();
556                 }
557                 d->Destroy ();
558         }
559
560         bool should_close ()
561         {
562                 if (!JobManager::instance()->work_to_do ()) {
563                         return true;
564                 }
565
566                 wxMessageDialog* d = new wxMessageDialog (
567                         0,
568                         _("There are unfinished jobs; are you sure you want to quit?"),
569                         _("Unfinished jobs"),
570                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
571                         );
572
573                 bool const r = d->ShowModal() == wxID_YES;
574                 d->Destroy ();
575                 return r;
576         }
577                 
578         void close (wxCloseEvent& ev)
579         {
580                 if (!should_close ()) {
581                         ev.Veto ();
582                         return;
583                 }
584
585                 /* We don't want to hear about any more configuration changes, since they
586                    cause the File menu to be altered, which itself will be deleted around
587                    now (without, as far as I can see, any way for us to find out).
588                 */
589                 _config_changed_connection.disconnect ();
590                 
591                 maybe_save_then_delete_film ();
592                 ev.Skip ();
593         }
594
595         void set_menu_sensitivity ()
596         {
597                 list<shared_ptr<Job> > jobs = JobManager::instance()->get ();
598                 list<shared_ptr<Job> >::iterator i = jobs.begin();
599                 while (i != jobs.end() && dynamic_pointer_cast<TranscodeJob> (*i) == 0) {
600                         ++i;
601                 }
602                 bool const dcp_creation = (i != jobs.end ()) && !(*i)->finished ();
603                 bool const have_cpl = _film && !_film->cpls().empty ();
604                 bool const have_selected_video_content = !_film_editor->content_panel()->selected_video().empty();
605                 
606                 for (map<wxMenuItem*, int>::iterator j = menu_items.begin(); j != menu_items.end(); ++j) {
607                         
608                         bool enabled = true;
609                         
610                         if ((j->second & NEEDS_FILM) && !_film) {
611                                 enabled = false;
612                         }
613                         
614                         if ((j->second & NOT_DURING_DCP_CREATION) && dcp_creation) {
615                                 enabled = false;
616                         }
617                         
618                         if ((j->second & NEEDS_CPL) && !have_cpl) {
619                                 enabled = false;
620                         }
621                         
622                         if ((j->second & NEEDS_SELECTED_VIDEO_CONTENT) && !have_selected_video_content) {
623                                 enabled = false;
624                         }
625                         
626                         j->first->Enable (enabled);
627                 }
628         }
629
630         void maybe_save_then_delete_film ()
631         {
632                 if (!_film) {
633                         return;
634                 }
635                 
636                 if (_film->dirty ()) {
637                         FilmChangedDialog d (_film->name ());
638                         switch (d.run ()) {
639                         case wxID_NO:
640                                 break;
641                         case wxID_YES:
642                                 _film->write_metadata ();
643                                 break;
644                         }
645                 }
646                 
647                 _film.reset ();
648         }
649
650         void add_item (wxMenu* menu, wxString text, int id, int sens)
651         {
652                 wxMenuItem* item = menu->Append (id, text);
653                 menu_items.insert (make_pair (item, sens));
654         }
655         
656         void setup_menu (wxMenuBar* m)
657         {
658                 _file_menu = new wxMenu;
659                 add_item (_file_menu, _("New...\tCtrl-N"), ID_file_new, ALWAYS);
660                 add_item (_file_menu, _("&Open...\tCtrl-O"), ID_file_open, ALWAYS);
661                 _file_menu->AppendSeparator ();
662                 add_item (_file_menu, _("&Save\tCtrl-S"), ID_file_save, NEEDS_FILM);
663                 _file_menu->AppendSeparator ();
664                 add_item (_file_menu, _("&Properties..."), ID_file_properties, NEEDS_FILM);
665
666                 _history_position = _file_menu->GetMenuItems().GetCount();
667
668 #ifndef __WXOSX__       
669                 _file_menu->AppendSeparator ();
670 #endif
671         
672 #ifdef __WXOSX__        
673                 add_item (_file_menu, _("&Exit"), wxID_EXIT, ALWAYS);
674 #else
675                 add_item (_file_menu, _("&Quit"), wxID_EXIT, ALWAYS);
676 #endif  
677         
678 #ifdef __WXOSX__        
679                 add_item (_file_menu, _("&Preferences...\tCtrl-P"), wxID_PREFERENCES, ALWAYS);
680 #else
681                 wxMenu* edit = new wxMenu;
682                 add_item (edit, _("&Preferences...\tCtrl-P"), wxID_PREFERENCES, ALWAYS);
683 #endif
684
685                 wxMenu* content = new wxMenu;
686                 add_item (content, _("Scale to fit &width"), ID_content_scale_to_fit_width, NEEDS_FILM | NEEDS_SELECTED_VIDEO_CONTENT);
687                 add_item (content, _("Scale to fit &height"), ID_content_scale_to_fit_height, NEEDS_FILM | NEEDS_SELECTED_VIDEO_CONTENT);
688                 
689                 wxMenu* jobs_menu = new wxMenu;
690                 add_item (jobs_menu, _("&Make DCP\tCtrl-M"), ID_jobs_make_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION);
691                 add_item (jobs_menu, _("Make &KDMs...\tCtrl-K"), ID_jobs_make_kdms, NEEDS_FILM);
692                 add_item (jobs_menu, _("&Send DCP to TMS"), ID_jobs_send_dcp_to_tms, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
693                 add_item (jobs_menu, _("S&how DCP"), ID_jobs_show_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
694
695                 wxMenu* tools = new wxMenu;
696                 add_item (tools, _("Hints..."), ID_tools_hints, 0);
697                 add_item (tools, _("Encoding servers..."), ID_tools_encoding_servers, 0);
698                 add_item (tools, _("Check for updates"), ID_tools_check_for_updates, 0);
699                 tools->AppendSeparator ();
700                 add_item (tools, _("Restore default preferences"), ID_tools_restore_default_preferences, ALWAYS);
701                 
702                 wxMenu* help = new wxMenu;
703 #ifdef __WXOSX__        
704                 add_item (help, _("About DCP-o-matic"), wxID_ABOUT, ALWAYS);
705 #else   
706                 add_item (help, _("About"), wxID_ABOUT, ALWAYS);
707 #endif  
708                 add_item (help, _("Report a problem..."), ID_help_report_a_problem, ALWAYS);
709                 
710                 m->Append (_file_menu, _("&File"));
711 #ifndef __WXOSX__       
712                 m->Append (edit, _("&Edit"));
713 #endif
714                 m->Append (content, _("&Content"));
715                 m->Append (jobs_menu, _("&Jobs"));
716                 m->Append (tools, _("&Tools"));
717                 m->Append (help, _("&Help"));
718         }
719
720         void config_changed ()
721         {
722                 for (int i = 0; i < _history_items; ++i) {
723                         delete _file_menu->Remove (ID_file_history + i);
724                 }
725
726                 if (_history_separator) {
727                         _file_menu->Remove (_history_separator);
728                 }
729                 delete _history_separator;
730                 _history_separator = 0;
731                 
732                 int pos = _history_position;
733                 
734                 vector<boost::filesystem::path> history = Config::instance()->history ();
735                 
736                 if (!history.empty ()) {
737                         _history_separator = _file_menu->InsertSeparator (pos++);
738                 }
739                 
740                 for (size_t i = 0; i < history.size(); ++i) {
741                         SafeStringStream s;
742                         if (i < 9) {
743                                 s << "&" << (i + 1) << " ";
744                         }
745                         s << history[i].string();
746                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s.str ()));
747                 }
748
749                 _history_items = history.size ();
750         }
751         
752         FilmEditor* _film_editor;
753         FilmViewer* _film_viewer;
754         HintsDialog* _hints_dialog;
755         ServersListDialog* _servers_list_dialog;
756         wxPreferencesEditor* _config_dialog;
757         wxMenu* _file_menu;
758         shared_ptr<Film> _film;
759         int _history_items;
760         int _history_position;
761         wxMenuItem* _history_separator;
762         boost::signals2::scoped_connection _config_changed_connection;
763 };
764
765 static const wxCmdLineEntryDesc command_line_description[] = {
766         { wxCMD_LINE_SWITCH, "n", "new", "create new film", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
767         { wxCMD_LINE_OPTION, "c", "content", "add content file", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
768         { wxCMD_LINE_PARAM, 0, 0, "film to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
769         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
770 };
771
772 /** @class App
773  *  @brief The magic App class for wxWidgets.
774  */
775 class App : public wxApp
776 {
777 public:
778         App ()
779                 : wxApp ()
780                 , _frame (0)
781         {}
782
783 private:        
784                 
785         bool OnInit ()
786         try
787         {
788                 SetAppName (_("DCP-o-matic"));
789                 
790                 if (!wxApp::OnInit()) {
791                         return false;
792                 }
793                 
794 #ifdef DCPOMATIC_LINUX  
795                 unsetenv ("UBUNTU_MENUPROXY");
796 #endif
797
798 #ifdef __WXOSX__                
799                 ProcessSerialNumber serial;
800                 GetCurrentProcess (&serial);
801                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
802 #endif          
803
804                 wxInitAllImageHandlers ();
805
806                 /* Enable i18n; this will create a Config object
807                    to look for a force-configured language.  This Config
808                    object will be wrong, however, because dcpomatic_setup
809                    hasn't yet been called and there aren't any filters etc.
810                    set up yet.
811                 */
812                 dcpomatic_setup_i18n ();
813
814                 /* Set things up, including filters etc.
815                    which will now be internationalised correctly.
816                 */
817                 dcpomatic_setup ();
818
819                 /* Force the configuration to be re-loaded correctly next
820                    time it is needed.
821                 */
822                 Config::drop ();
823
824                 _frame = new Frame (_("DCP-o-matic"));
825                 SetTopWindow (_frame);
826                 _frame->Maximize ();
827                 _frame->Show ();
828
829                 if (!_film_to_load.empty() && boost::filesystem::is_directory (_film_to_load)) {
830                         try {
831                                 _frame->load_film (_film_to_load);
832                         } catch (exception& e) {
833                                 error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load film %1 (%2)")), _film_to_load, e.what())));
834                         }
835                 }
836
837                 if (!_film_to_create.empty ()) {
838                         _frame->new_film (_film_to_create);
839                         if (!_content_to_add.empty ()) {
840                                 _frame->film()->examine_and_add_content (content_factory (_frame->film(), _content_to_add));
841                         }
842                 }
843
844                 signal_manager = new wxSignalManager (this);
845                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
846
847                 Bind (wxEVT_TIMER, boost::bind (&App::check, this));
848                 _timer.reset (new wxTimer (this));
849                 _timer->Start (1000);
850
851                 UpdateChecker::instance()->StateChanged.connect (boost::bind (&App::update_checker_state_changed, this));
852                 if (Config::instance()->check_for_updates ()) {
853                         UpdateChecker::instance()->run ();
854                 }
855
856                 return true;
857         }
858         catch (exception& e)
859         {
860                 error_dialog (0, wxString::Format ("DCP-o-matic could not start: %s", e.what ()));
861                 return true;
862         }
863
864         void OnInitCmdLine (wxCmdLineParser& parser)
865         {
866                 parser.SetDesc (command_line_description);
867                 parser.SetSwitchChars (wxT ("-"));
868         }
869
870         bool OnCmdLineParsed (wxCmdLineParser& parser)
871         {
872                 if (parser.GetParamCount() > 0) {
873                         if (parser.Found (wxT ("new"))) {
874                                 _film_to_create = wx_to_std (parser.GetParam (0));
875                         } else {
876                                 _film_to_load = wx_to_std (parser.GetParam (0));
877                         }
878                 }
879
880                 wxString content;
881                 if (parser.Found (wxT ("content"), &content)) {
882                         _content_to_add = wx_to_std (content);
883                 }
884
885                 return true;
886         }
887
888         /* An unhandled exception has occurred inside the main event loop */
889         bool OnExceptionInMainLoop ()
890         {
891                 try {
892                         throw;
893                 } catch (FileError& e) {
894                         error_dialog (0, wxString::Format (_("An exception occurred: %s in %s.\n\n" + REPORT_PROBLEM), e.what(), e.file().string().c_str ()));
895                 } catch (exception& e) {
896                         error_dialog (0, wxString::Format (_("An exception occurred: %s.\n\n"), e.what ()) + "  " + REPORT_PROBLEM);
897                 } catch (...) {
898                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
899                 }
900
901                 /* This will terminate the program */
902                 return false;
903         }
904         
905         void OnUnhandledException ()
906         {
907                 error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
908         }
909
910         void idle ()
911         {
912                 signal_manager->ui_idle ();
913         }
914
915         void check ()
916         {
917                 try {
918                         ServerFinder::instance()->rethrow ();
919                 } catch (exception& e) {
920                         error_dialog (0, std_to_wx (e.what ()));
921                 }
922         }
923
924         void update_checker_state_changed ()
925         {
926                 UpdateChecker* uc = UpdateChecker::instance ();
927                 if (uc->state() == UpdateChecker::YES && (uc->stable() || uc->test())) {
928                         UpdateDialog* dialog = new UpdateDialog (_frame, uc->stable (), uc->test ());
929                         dialog->ShowModal ();
930                         dialog->Destroy ();
931                 } else if (uc->state() == UpdateChecker::FAILED) {
932                         if (!UpdateChecker::instance()->last_emit_was_first ()) {
933                                 error_dialog (_frame, _("The DCP-o-matic download server could not be contacted."));
934                         }
935                 } else {
936                         if (!UpdateChecker::instance()->last_emit_was_first ()) {
937                                 error_dialog (_frame, _("There are no new versions of DCP-o-matic available."));
938                         }
939                 }
940         }
941
942         Frame* _frame;
943         shared_ptr<wxTimer> _timer;
944         string _film_to_load;
945         string _film_to_create;
946         string _content_to_add;
947 };
948
949 IMPLEMENT_APP (App)