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