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