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