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