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