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