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