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