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