b4ec1d77da9d754db678c75e191e93af9ddba35a
[dcpomatic.git] / src / tools / dcpomatic.cc
1 /*
2     Copyright (C) 2012-2013 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <iostream>
21 #include <fstream>
22 #include <boost/filesystem.hpp>
23 #ifdef __WXMSW__
24 #include <shellapi.h>
25 #endif
26 #ifdef __WXOSX__
27 #include <ApplicationServices/ApplicationServices.h>
28 #endif
29 #include <wx/generic/aboutdlgg.h>
30 #include <wx/stdpaths.h>
31 #include <wx/cmdline.h>
32 #include "wx/film_viewer.h"
33 #include "wx/film_editor.h"
34 #include "wx/job_manager_view.h"
35 #include "wx/config_dialog.h"
36 #include "wx/job_wrapper.h"
37 #include "wx/wx_util.h"
38 #include "wx/new_film_dialog.h"
39 #include "wx/properties_dialog.h"
40 #include "wx/wx_ui_signaller.h"
41 #include "wx/about_dialog.h"
42 #include "wx/kdm_dialog.h"
43 #include "wx/servers_list_dialog.h"
44 #include "wx/hints_dialog.h"
45 #include "lib/film.h"
46 #include "lib/config.h"
47 #include "lib/util.h"
48 #include "lib/version.h"
49 #include "lib/ui_signaller.h"
50 #include "lib/log.h"
51 #include "lib/job_manager.h"
52 #include "lib/transcode_job.h"
53 #include "lib/exceptions.h"
54 #include "lib/cinema.h"
55 #include "lib/kdm.h"
56
57 using std::cout;
58 using std::string;
59 using std::wstring;
60 using std::stringstream;
61 using std::map;
62 using std::make_pair;
63 using std::list;
64 using std::exception;
65 using boost::shared_ptr;
66 using boost::dynamic_pointer_cast;
67
68 static FilmEditor* film_editor = 0;
69 static FilmViewer* film_viewer = 0;
70 static shared_ptr<Film> film;
71 static std::string log_level;
72 static std::string film_to_load;
73 static std::string film_to_create;
74 static wxMenu* jobs_menu = 0;
75
76 static void set_menu_sensitivity ();
77
78 class FilmChangedDialog
79 {
80 public:
81         FilmChangedDialog ()
82         {
83                 _dialog = new wxMessageDialog (
84                         0,
85                         wxString::Format (_("Save changes to film \"%s\" before closing?"), std_to_wx (film->name ()).data()),
86                         _("Film changed"),
87                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
88                         );
89         }
90
91         ~FilmChangedDialog ()
92         {
93                 _dialog->Destroy ();
94         }
95
96         int run ()
97         {
98                 return _dialog->ShowModal ();
99         }
100
101 private:
102         /* Not defined */
103         FilmChangedDialog (FilmChangedDialog const &);
104         
105         wxMessageDialog* _dialog;
106 };
107
108
109 void
110 maybe_save_then_delete_film ()
111 {
112         if (!film) {
113                 return;
114         }
115                         
116         if (film->dirty ()) {
117                 FilmChangedDialog d;
118                 switch (d.run ()) {
119                 case wxID_NO:
120                         break;
121                 case wxID_YES:
122                         film->write_metadata ();
123                         break;
124                 }
125         }
126         
127         film.reset ();
128 }
129
130 #define ALWAYS                  0x0
131 #define NEEDS_FILM              0x1
132 #define NOT_DURING_DCP_CREATION 0x2
133 #define NEEDS_DCP               0x4
134
135 map<wxMenuItem*, int> menu_items;
136         
137 void
138 add_item (wxMenu* menu, wxString text, int id, int sens)
139 {
140         wxMenuItem* item = menu->Append (id, text);
141         menu_items.insert (make_pair (item, sens));
142 }
143
144 void
145 set_menu_sensitivity ()
146 {
147         list<shared_ptr<Job> > jobs = JobManager::instance()->get ();
148         list<shared_ptr<Job> >::iterator i = jobs.begin();
149         while (i != jobs.end() && dynamic_pointer_cast<TranscodeJob> (*i) == 0) {
150                 ++i;
151         }
152         bool const dcp_creation = (i != jobs.end ()) && !(*i)->finished ();
153         bool const have_dcp = film && !film->dcps().empty ();
154
155         for (map<wxMenuItem*, int>::iterator j = menu_items.begin(); j != menu_items.end(); ++j) {
156
157                 bool enabled = true;
158
159                 if ((j->second & NEEDS_FILM) && film == 0) {
160                         enabled = false;
161                 }
162
163                 if ((j->second & NOT_DURING_DCP_CREATION) && dcp_creation) {
164                         enabled = false;
165                 }
166
167                 if ((j->second & NEEDS_DCP) && !have_dcp) {
168                         enabled = false;
169                 }
170                 
171                 j->first->Enable (enabled);
172         }
173 }
174
175 enum {
176         ID_file_new = 1,
177         ID_file_open,
178         ID_file_save,
179         ID_file_properties,
180         ID_jobs_make_dcp,
181         ID_jobs_make_kdms,
182         ID_jobs_send_dcp_to_tms,
183         ID_jobs_show_dcp,
184         ID_tools_hints,
185         ID_tools_encoding_servers,
186 };
187
188 void
189 setup_menu (wxMenuBar* m)
190 {
191         wxMenu* file = new wxMenu;
192         add_item (file, _("New..."), ID_file_new, ALWAYS);
193         add_item (file, _("&Open..."), ID_file_open, ALWAYS);
194         file->AppendSeparator ();
195         add_item (file, _("&Save"), ID_file_save, NEEDS_FILM);
196         file->AppendSeparator ();
197         add_item (file, _("&Properties..."), ID_file_properties, NEEDS_FILM);
198 #ifndef __WXOSX__       
199         file->AppendSeparator ();
200 #endif
201
202 #ifdef __WXOSX__        
203         add_item (file, _("&Exit"), wxID_EXIT, ALWAYS);
204 #else
205         add_item (file, _("&Quit"), wxID_EXIT, ALWAYS);
206 #endif  
207         
208
209 #ifdef __WXOSX__        
210         add_item (file, _("&Preferences..."), wxID_PREFERENCES, ALWAYS);
211 #else
212         wxMenu* edit = new wxMenu;
213         add_item (edit, _("&Preferences..."), wxID_PREFERENCES, ALWAYS);
214 #endif  
215
216         jobs_menu = new wxMenu;
217         add_item (jobs_menu, _("&Make DCP"), ID_jobs_make_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION);
218         add_item (jobs_menu, _("Make &KDMs..."), ID_jobs_make_kdms, NEEDS_FILM | NEEDS_DCP);
219         add_item (jobs_menu, _("&Send DCP to TMS"), ID_jobs_send_dcp_to_tms, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_DCP);
220         add_item (jobs_menu, _("S&how DCP"), ID_jobs_show_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_DCP);
221
222         wxMenu* tools = new wxMenu;
223         add_item (tools, _("Hints..."), ID_tools_hints, 0);
224         add_item (tools, _("Encoding Servers..."), ID_tools_encoding_servers, 0);
225
226         wxMenu* help = new wxMenu;
227 #ifdef __WXOSX__        
228         add_item (help, _("About DCP-o-matic"), wxID_ABOUT, ALWAYS);
229 #else   
230         add_item (help, _("About"), wxID_ABOUT, ALWAYS);
231 #endif  
232
233         m->Append (file, _("&File"));
234 #ifndef __WXOSX__       
235         m->Append (edit, _("&Edit"));
236 #endif  
237         m->Append (jobs_menu, _("&Jobs"));
238         m->Append (tools, _("&Tools"));
239         m->Append (help, _("&Help"));
240 }
241
242 class Frame : public wxFrame
243 {
244 public:
245         Frame (wxString const & title)
246                 : wxFrame (NULL, -1, title)
247                 , _servers_list_dialog (0)
248                 , _hints_dialog (0)
249         {
250 #ifdef DCPOMATIC_WINDOWS_CONSOLE                
251                 AllocConsole();
252                 
253                 HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
254                 int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
255                 FILE* hf_out = _fdopen(hCrt, "w");
256                 setvbuf(hf_out, NULL, _IONBF, 1);
257                 *stdout = *hf_out;
258                 
259                 HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
260                 hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
261                 FILE* hf_in = _fdopen(hCrt, "r");
262                 setvbuf(hf_in, NULL, _IONBF, 128);
263                 *stdin = *hf_in;
264 #endif
265
266                 wxMenuBar* bar = new wxMenuBar;
267                 setup_menu (bar);
268                 SetMenuBar (bar);
269
270                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::file_new, this),               ID_file_new);
271                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::file_open, this),              ID_file_open);
272                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::file_save, this),              ID_file_save);
273                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::file_properties, this),        ID_file_properties);
274                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::file_exit, this),              wxID_EXIT);
275                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::edit_preferences, this),       wxID_PREFERENCES);
276                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::jobs_make_dcp, this),          ID_jobs_make_dcp);
277                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::jobs_make_kdms, this),         ID_jobs_make_kdms);
278                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::jobs_send_dcp_to_tms, this),   ID_jobs_send_dcp_to_tms);
279                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::jobs_show_dcp, this),          ID_jobs_show_dcp);
280                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::tools_hints, this),            ID_tools_hints);
281                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::tools_encoding_servers, this), ID_tools_encoding_servers);
282                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&Frame::help_about, this),             wxID_ABOUT);
283
284                 Bind (wxEVT_CLOSE_WINDOW, boost::bind (&Frame::close, this, _1));
285
286                 /* Use a panel as the only child of the Frame so that we avoid
287                    the dark-grey background on Windows.
288                 */
289                 wxPanel* overall_panel = new wxPanel (this, wxID_ANY);
290
291                 film_editor = new FilmEditor (film, overall_panel);
292                 film_viewer = new FilmViewer (film, overall_panel);
293                 JobManagerView* job_manager_view = new JobManagerView (overall_panel, static_cast<JobManagerView::Buttons> (0));
294
295                 wxBoxSizer* right_sizer = new wxBoxSizer (wxVERTICAL);
296                 right_sizer->Add (film_viewer, 2, wxEXPAND | wxALL, 6);
297                 right_sizer->Add (job_manager_view, 1, wxEXPAND | wxALL, 6);
298
299                 wxBoxSizer* main_sizer = new wxBoxSizer (wxHORIZONTAL);
300                 main_sizer->Add (film_editor, 1, wxEXPAND | wxALL, 6);
301                 main_sizer->Add (right_sizer, 2, wxEXPAND | wxALL, 6);
302
303                 set_menu_sensitivity ();
304
305                 film_editor->FileChanged.connect (bind (&Frame::file_changed, this, _1));
306                 if (film) {
307                         file_changed (film->directory ());
308                 } else {
309                         file_changed ("");
310                 }
311
312                 JobManager::instance()->ActiveJobsChanged.connect (boost::bind (set_menu_sensitivity));
313
314                 set_film ();
315                 overall_panel->SetSizer (main_sizer);
316         }
317
318 private:
319
320         void set_film ()
321         {
322                 film_viewer->set_film (film);
323                 film_editor->set_film (film);
324                 set_menu_sensitivity ();
325         }
326
327         void file_changed (boost::filesystem::path f)
328         {
329                 stringstream s;
330                 s << wx_to_std (_("DCP-o-matic"));
331                 if (!f.empty ()) {
332                         s << " - " << f.string ();
333                 }
334                 
335                 SetTitle (std_to_wx (s.str()));
336         }
337         
338         void file_new ()
339         {
340                 NewFilmDialog* d = new NewFilmDialog (this);
341                 int const r = d->ShowModal ();
342                 
343                 if (r == wxID_OK) {
344
345                         if (boost::filesystem::is_directory (d->get_path()) && !boost::filesystem::is_empty(d->get_path())) {
346                                 if (!confirm_dialog (
347                                             this,
348                                             std_to_wx (
349                                                     String::compose (wx_to_std (_("The directory %1 already exists and is not empty.  "
350                                                                                   "Are you sure you want to use it?")),
351                                                                      d->get_path().string().c_str())
352                                                     )
353                                             )) {
354                                         return;
355                                 }
356                         } else if (boost::filesystem::is_regular_file (d->get_path())) {
357                                 error_dialog (
358                                         this,
359                                         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())
360                                         );
361                                 return;
362                         }
363                         
364                         maybe_save_then_delete_film ();
365                         film.reset (new Film (d->get_path ()));
366                         film->write_metadata ();
367                         film->log()->set_level (log_level);
368                         film->set_name (boost::filesystem::path (d->get_path()).filename().generic_string());
369                         set_film ();
370                 }
371                 
372                 d->Destroy ();
373         }
374
375         void file_open ()
376         {
377                 wxDirDialog* c = new wxDirDialog (
378                         this,
379                         _("Select film to open"),
380                         std_to_wx (Config::instance()->default_directory_or (wx_to_std (wxStandardPaths::Get().GetDocumentsDir())).string ()),
381                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
382                         );
383                 
384                 int r;
385                 while (1) {
386                         r = c->ShowModal ();
387                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
388                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
389                         } else {
390                                 break;
391                         }
392                 }
393                         
394                 if (r == wxID_OK) {
395                         maybe_save_then_delete_film ();
396                         try {
397                                 film.reset (new Film (wx_to_std (c->GetPath ())));
398                                 film->read_metadata ();
399                                 film->log()->set_level (log_level);
400                                 set_film ();
401                         } catch (std::exception& e) {
402                                 wxString p = c->GetPath ();
403                                 wxCharBuffer b = p.ToUTF8 ();
404                                 error_dialog (this, wxString::Format (_("Could not open film at %s (%s)"), p.data(), std_to_wx (e.what()).data()));
405                         }
406                 }
407
408                 c->Destroy ();
409         }
410
411         void file_save ()
412         {
413                 film->write_metadata ();
414         }
415
416         void file_properties ()
417         {
418                 PropertiesDialog* d = new PropertiesDialog (this, film);
419                 d->ShowModal ();
420                 d->Destroy ();
421         }
422         
423         void file_exit ()
424         {
425                 if (!should_close ()) {
426                         return;
427                 }
428                 
429                 maybe_save_then_delete_film ();
430                 Close (true);
431         }
432
433         void edit_preferences ()
434         {
435                 ConfigDialog* d = new ConfigDialog (this);
436                 d->ShowModal ();
437                 d->Destroy ();
438                 Config::instance()->write ();
439         }
440
441         void jobs_make_dcp ()
442         {
443                 JobWrapper::make_dcp (this, film);
444         }
445
446         void jobs_make_kdms ()
447         {
448                 if (!film) {
449                         return;
450                 }
451                 
452                 KDMDialog* d = new KDMDialog (this, film);
453                 if (d->ShowModal () != wxID_OK) {
454                         d->Destroy ();
455                         return;
456                 }
457
458                 try {
459                         if (d->write_to ()) {
460                                 write_kdm_files (film, d->screens (), d->dcp (), d->from (), d->until (), d->directory ());
461                         } else {
462                                 email_kdms (film, d->screens (), d->dcp (), d->from (), d->until ());
463                         }
464                 } catch (KDMError& e) {
465                         error_dialog (this, e.what ());
466                 }
467         
468                 d->Destroy ();
469         }
470         
471         void jobs_send_dcp_to_tms ()
472         {
473                 film->send_dcp_to_tms ();
474         }
475
476         void jobs_show_dcp ()
477         {
478 #ifdef __WXMSW__
479                 string d = film->directory().string ();
480                 wstring w;
481                 w.assign (d.begin(), d.end());
482                 ShellExecute (0, L"open", w.c_str(), 0, 0, SW_SHOWDEFAULT);
483 #else
484                 int r = system ("which nautilus");
485                 if (WEXITSTATUS (r) == 0) {
486                         r = system (string ("nautilus " + film->directory().string()).c_str ());
487                         if (WEXITSTATUS (r)) {
488                                 error_dialog (this, _("Could not show DCP (could not run nautilus)"));
489                         }
490                 } else {
491                         int r = system ("which konqueror");
492                         if (WEXITSTATUS (r) == 0) {
493                                 r = system (string ("konqueror " + film->directory().string()).c_str ());
494                                 if (WEXITSTATUS (r)) {
495                                         error_dialog (this, _("Could not show DCP (could not run konqueror)"));
496                                 }
497                         }
498                 }
499 #endif          
500         }
501
502         void tools_hints ()
503         {
504                 if (!_hints_dialog) {
505                         _hints_dialog = new HintsDialog (this, film);
506                 }
507
508                 _hints_dialog->Show ();
509         }
510
511         void tools_encoding_servers ()
512         {
513                 if (!_servers_list_dialog) {
514                         _servers_list_dialog = new ServersListDialog (this);
515                 }
516
517                 _servers_list_dialog->Show ();
518         }
519
520         void help_about ()
521         {
522                 AboutDialog* d = new AboutDialog (this);
523                 d->ShowModal ();
524                 d->Destroy ();
525         }
526
527         bool should_close ()
528         {
529                 if (!JobManager::instance()->work_to_do ()) {
530                         return true;
531                 }
532
533                 wxMessageDialog* d = new wxMessageDialog (
534                         0,
535                         _("There are unfinished jobs; are you sure you want to quit?"),
536                         _("Unfinished jobs"),
537                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
538                         );
539
540                 bool const r = d->ShowModal() == wxID_YES;
541                 d->Destroy ();
542                 return r;
543         }
544                 
545         void close (wxCloseEvent& ev)
546         {
547                 if (!should_close ()) {
548                         ev.Veto ();
549                         return;
550                 }
551
552                 ev.Skip ();
553         }
554
555         HintsDialog* _hints_dialog;
556         ServersListDialog* _servers_list_dialog;
557 };
558
559 static const wxCmdLineEntryDesc command_line_description[] = {
560         { wxCMD_LINE_OPTION, "l", "log", "set log level (silent, verbose or timing)", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
561         { wxCMD_LINE_SWITCH, "n", "new", "create new film", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
562         { wxCMD_LINE_PARAM, 0, 0, "film to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_MULTIPLE | wxCMD_LINE_PARAM_OPTIONAL },
563         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
564 };
565
566 class App : public wxApp
567 {
568         bool OnInit ()
569         try
570         {
571                 SetAppName (_("DCP-o-matic"));
572                 
573                 if (!wxApp::OnInit()) {
574                         return false;
575                 }
576                 
577 #ifdef DCPOMATIC_LINUX  
578                 unsetenv ("UBUNTU_MENUPROXY");
579 #endif
580
581 #ifdef __WXOSX__                
582                 ProcessSerialNumber serial;
583                 GetCurrentProcess (&serial);
584                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
585 #endif          
586
587                 wxInitAllImageHandlers ();
588
589                 /* Enable i18n; this will create a Config object
590                    to look for a force-configured language.  This Config
591                    object will be wrong, however, because dcpomatic_setup
592                    hasn't yet been called and there aren't any scalers, filters etc.
593                    set up yet.
594                 */
595                 dcpomatic_setup_i18n ();
596
597                 /* Set things up, including scalers / filters etc.
598                    which will now be internationalised correctly.
599                 */
600                 dcpomatic_setup ();
601
602                 /* Force the configuration to be re-loaded correctly next
603                    time it is needed.
604                 */
605                 Config::drop ();
606
607                 if (!film_to_load.empty() && boost::filesystem::is_directory (film_to_load)) {
608                         try {
609                                 film.reset (new Film (film_to_load));
610                                 film->read_metadata ();
611                                 film->log()->set_level (log_level);
612                         } catch (exception& e) {
613                                 error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load film %1 (%2)")), film_to_load, e.what())));
614                         }
615                 }
616
617                 if (!film_to_create.empty ()) {
618                         film.reset (new Film (film_to_create));
619                         film->write_metadata ();
620                         film->log()->set_level (log_level);
621                         film->set_name (boost::filesystem::path (film_to_create).filename().generic_string ());
622                 }
623
624                 Frame* f = new Frame (_("DCP-o-matic"));
625                 SetTopWindow (f);
626                 f->Maximize ();
627                 f->Show ();
628
629                 ui_signaller = new wxUISignaller (this);
630                 this->Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
631
632                 return true;
633         }
634         catch (exception& e)
635         {
636                 error_dialog (0, wxString::Format ("DCP-o-matic could not start: %s", e.what ()));
637                 return true;
638         }
639
640         void OnInitCmdLine (wxCmdLineParser& parser)
641         {
642                 parser.SetDesc (command_line_description);
643                 parser.SetSwitchChars (wxT ("-"));
644         }
645
646         bool OnCmdLineParsed (wxCmdLineParser& parser)
647         {
648                 if (parser.GetParamCount() > 0) {
649                         if (parser.Found (wxT ("new"))) {
650                                 film_to_create = wx_to_std (parser.GetParam (0));
651                         } else {
652                                 film_to_load = wx_to_std (parser.GetParam(0));
653                         }
654                 }
655
656                 wxString log;
657                 if (parser.Found (wxT ("log"), &log)) {
658                         log_level = wx_to_std (log);
659                 }
660
661                 return true;
662         }
663
664         void idle ()
665         {
666                 ui_signaller->ui_idle ();
667         }
668 };
669
670 IMPLEMENT_APP (App)