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