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