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