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