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