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