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