Supporters update.
[dcpomatic.git] / src / tools / dcpomatic_disk.cc
1 /*
2     Copyright (C) 2019-2021 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21
22 #include "wx/disk_warning_dialog.h"
23 #include "wx/drive_wipe_warning_dialog.h"
24 #include "wx/editable_list.h"
25 #include "wx/id.h"
26 #include "wx/job_manager_view.h"
27 #include "wx/message_dialog.h"
28 #include "wx/try_unmount_dialog.h"
29 #include "wx/wx_util.h"
30 #include "wx/wx_signal_manager.h"
31 #include "wx/wx_util.h"
32 #include "lib/config.h"
33 #include "lib/constants.h"
34 #include "lib/copy_to_drive_job.h"
35 #include "lib/cross.h"
36 #include "lib/dcpomatic_log.h"
37 #include "lib/disk_writer_messages.h"
38 #include "lib/file_log.h"
39 #include "lib/job_manager.h"
40 #include "lib/signal_manager.h"
41 #include "lib/util.h"
42 #include "lib/version.h"
43 #include <dcp/filesystem.h>
44 #include <dcp/warnings.h>
45 #include <wx/cmdline.h>
46 #include <wx/wx.h>
47 LIBDCP_DISABLE_WARNINGS
48 #include <boost/process.hpp>
49 LIBDCP_ENABLE_WARNINGS
50 #ifdef DCPOMATIC_WINDOWS
51 #include <boost/process/windows.hpp>
52 #endif
53 #ifdef DCPOMATIC_OSX
54 #include <notify.h>
55 #endif
56
57
58 using std::cerr;
59 using std::cout;
60 using std::exception;
61 using std::make_shared;
62 using std::shared_ptr;
63 using std::string;
64 using std::vector;
65 using boost::optional;
66 #if BOOST_VERSION >= 106100
67 using namespace boost::placeholders;
68 #endif
69
70
71 #ifdef DCPOMATIC_OSX
72 enum {
73         ID_tools_uninstall = DCPOMATIC_MAIN_MENU,
74 };
75 #endif
76
77
78 class DirDialogWrapper : public wxDirDialog
79 {
80 public:
81         DirDialogWrapper (wxWindow* parent)
82                 : wxDirDialog (parent, _("Choose a DCP folder"), wxT(""), wxDD_DIR_MUST_EXIST)
83         {
84
85         }
86
87         boost::optional<boost::filesystem::path> get () const
88         {
89                 auto const dcp = boost::filesystem::path(wx_to_std(GetPath()));
90                 if (!dcp::filesystem::exists(dcp / "ASSETMAP") && !dcp::filesystem::exists(dcp / "ASSETMAP.xml")) {
91                         error_dialog (nullptr, _("No ASSETMAP or ASSETMAP.xml found in this folder.  Please choose a DCP folder."));
92                         return {};
93                 }
94
95                 return dcp;
96         }
97
98         void set (boost::filesystem::path)
99         {
100                 /* Not used */
101         }
102 };
103
104
105 class DOMFrame : public wxFrame
106 {
107 public:
108         explicit DOMFrame (wxString const & title)
109                 : wxFrame (nullptr, wxID_ANY, title)
110                 , _nanomsg (true)
111                 , _sizer (new wxBoxSizer(wxVERTICAL))
112         {
113 #ifdef DCPOMATIC_OSX
114                 auto bar = new wxMenuBar;
115                 auto tools = new wxMenu;
116                 tools->Append(ID_tools_uninstall, _("Uninstall..."));
117                 bar->Append(tools, _("Tools"));
118                 SetMenuBar (bar);
119                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::uninstall, this), ID_tools_uninstall);
120 #endif
121
122                 /* Use a panel as the only child of the Frame so that we avoid
123                    the dark-grey background on Windows.
124                 */
125                 auto overall_panel = new wxPanel (this);
126                 auto s = new wxBoxSizer (wxHORIZONTAL);
127                 s->Add (overall_panel, 1, wxEXPAND);
128                 SetSizer (s);
129
130                 auto grid = new wxGridBagSizer (DCPOMATIC_SIZER_X_GAP, DCPOMATIC_SIZER_Y_GAP);
131
132                 int r = 0;
133                 add_label_to_sizer (grid, overall_panel, _("DCP"), true, wxGBPosition(r, 0));
134                 auto dcp_sizer = new wxBoxSizer (wxHORIZONTAL);
135                 auto dcps = new EditableList<boost::filesystem::path, DirDialogWrapper>(
136                         overall_panel,
137                         { EditableListColumn(_("DCP"), 300, true) },
138                         boost::bind(&DOMFrame::dcp_paths, this),
139                         boost::bind(&DOMFrame::set_dcp_paths, this, _1),
140                         [](boost::filesystem::path p, int) { return p.filename().string(); },
141                         EditableListTitle::INVISIBLE,
142                         EditableListButton::NEW | EditableListButton::REMOVE
143                         );
144
145                 dcp_sizer->Add(dcps, 1, wxALIGN_CENTER_VERTICAL, DCPOMATIC_SIZER_X_GAP);
146                 grid->Add(dcp_sizer, wxGBPosition(r, 1), wxDefaultSpan, wxEXPAND);
147                 ++r;
148
149                 add_label_to_sizer (grid, overall_panel, _("Drive"), true, wxGBPosition(r, 0));
150                 auto drive_sizer = new wxBoxSizer (wxHORIZONTAL);
151                 _drive = new wxChoice (overall_panel, wxID_ANY);
152                 drive_sizer->Add (_drive, 1, wxALIGN_CENTER_VERTICAL | wxRIGHT, DCPOMATIC_SIZER_X_GAP);
153                 _drive_refresh = new wxButton (overall_panel, wxID_ANY, _("Refresh"));
154                 drive_sizer->Add (_drive_refresh, 0);
155                 grid->Add (drive_sizer, wxGBPosition(r, 1), wxDefaultSpan, wxEXPAND);
156                 ++r;
157
158                 _jobs = new JobManagerView (overall_panel, false);
159                 grid->Add (_jobs, wxGBPosition(r, 0), wxGBSpan(6, 2), wxEXPAND);
160                 r += 6;
161
162                 _copy = new wxButton (overall_panel, wxID_ANY, _("Copy DCP"));
163                 grid->Add (_copy, wxGBPosition(r, 0), wxGBSpan(1, 2), wxEXPAND);
164                 ++r;
165
166                 grid->AddGrowableCol (1);
167
168                 _copy->Bind (wxEVT_BUTTON, boost::bind(&DOMFrame::copy, this));
169                 _drive->Bind (wxEVT_CHOICE, boost::bind(&DOMFrame::setup_sensitivity, this));
170                 _drive_refresh->Bind (wxEVT_BUTTON, boost::bind(&DOMFrame::drive_refresh, this));
171
172                 _sizer->Add (grid, 1, wxALL | wxEXPAND, DCPOMATIC_DIALOG_BORDER);
173                 overall_panel->SetSizer (_sizer);
174                 Fit ();
175                 SetSize (1024, GetSize().GetHeight() + 32);
176
177                 /* XXX: this is a hack, but I expect we'll need logs and I'm not sure if there's
178                  * a better place to put them.
179                  */
180                 dcpomatic_log = make_shared<FileLog>(State::write_path("disk.log"));
181                 dcpomatic_log->set_types (dcpomatic_log->types() | LogEntry::TYPE_DISK);
182                 LOG_DISK("dcpomatic_disk %1 started", dcpomatic_git_commit);
183
184                 drive_refresh ();
185
186                 Bind (wxEVT_SIZE, boost::bind(&DOMFrame::sized, this, _1));
187                 Bind (wxEVT_CLOSE_WINDOW, boost::bind(&DOMFrame::close, this, _1));
188
189                 JobManager::instance()->ActiveJobsChanged.connect(boost::bind(&DOMFrame::setup_sensitivity, this));
190
191 #ifdef DCPOMATIC_WINDOWS
192                 /* We must use ::shell here, it seems, to avoid error code 740 (related to privilege escalation) */
193                 LOG_DISK("Starting writer process %1", disk_writer_path().string());
194                 _writer = new boost::process::child (disk_writer_path(), boost::process::shell, boost::process::windows::hide);
195 #endif
196
197 #ifdef DCPOMATIC_LINUX
198                 if (getenv("DCPOMATIC_NO_START_WRITER")) {
199                         LOG_DISK_NC("Not starting writer process as DCPOMATIC_NO_START_WRITER is set");
200                 } else {
201                         LOG_DISK("Starting writer process %1", disk_writer_path().string());
202                         _writer = new boost::process::child (disk_writer_path());
203                 }
204 #endif
205
206 #ifdef DCPOMATIC_OSX
207                 LOG_DISK_NC("Sending notification to writer daemon");
208                 notify_post ("com.dcpomatic.disk.writer.start");
209 #endif
210         }
211
212         ~DOMFrame ()
213         {
214                 _nanomsg.send(DISK_WRITER_QUIT "\n", 2000);
215                 /* This seems really horrible but it's suggested by the examples on nanomsg.org, so...
216                  * Without this the quit is not received (at least sometimes) causing #2018.
217                  */
218                 dcpomatic_sleep_seconds (1);
219         }
220
221         void set_dcp_paths (vector<boost::filesystem::path> dcps)
222         {
223                 _dcp_paths = dcps;
224                 setup_sensitivity();
225         }
226
227 private:
228         vector<boost::filesystem::path> dcp_paths() const
229         {
230                 return _dcp_paths;
231         }
232
233         void sized (wxSizeEvent& ev)
234         {
235                 _sizer->Layout ();
236                 ev.Skip ();
237         }
238
239
240 #ifdef DCPOMATIC_OSX
241         void uninstall()
242         {
243                 system(String::compose("osascript \"%1/uninstall_disk.applescript\"", resources_path().string()).c_str());
244         }
245 #endif
246
247
248         bool should_close ()
249         {
250                 if (!JobManager::instance()->work_to_do()) {
251                         return true;
252                 }
253
254                 auto d = make_wx<wxMessageDialog>(
255                         nullptr,
256                         _("There are unfinished jobs; are you sure you want to quit?"),
257                         _("Unfinished jobs"),
258                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
259                         );
260
261                 return d->ShowModal() == wxID_YES;
262         }
263
264
265         void close (wxCloseEvent& ev)
266         {
267                 if (!should_close()) {
268                         ev.Veto ();
269                         return;
270                 }
271
272                 ev.Skip ();
273         }
274
275         void copy ()
276         {
277                 /* Check that the selected drive still exists and update its properties if so */
278                 drive_refresh ();
279                 if (_drive->GetSelection() == wxNOT_FOUND) {
280                         error_dialog (this, _("The disk you selected is no longer available.  Please choose another."));
281                         return;
282                 }
283
284                 DCPOMATIC_ASSERT (_drive->GetSelection() != wxNOT_FOUND);
285                 DCPOMATIC_ASSERT (!_dcp_paths.empty());
286
287                 auto ping = [this](int attempt) {
288                         if (_nanomsg.send(DISK_WRITER_PING "\n", 1000)) {
289                                 auto reply = DiskWriterBackEndResponse::read_from_nanomsg(_nanomsg, 1000);
290                                 if (reply && reply->type() == DiskWriterBackEndResponse::Type::PONG) {
291                                         return true;
292                                 } else if (reply) {
293                                         LOG_DISK("Unexpected response %1 to ping received (attempt %2)", static_cast<int>(reply->type()), attempt);
294                                 } else {
295                                         LOG_DISK("No reply received from ping (attempt %1)", attempt);
296                                 }
297                         } else {
298                                 LOG_DISK("Could not send ping to writer (attempt %1)", attempt);
299                         }
300                         dcpomatic_sleep_seconds (1);
301                         return false;
302                 };
303
304                 bool have_writer = false;
305                 for (int i = 0; i < 8; ++i) {
306                         if (ping(i + 1)) {
307                                 have_writer = true;
308                                 break;
309                         }
310                 }
311
312                 if (!have_writer) {
313 #if defined(DCPOMATIC_WINDOWS)
314                         auto m = make_wx<MessageDialog>(
315                                 this,
316                                 _("DCP-o-matic Disk Writer"),
317                                 _("Do you see a 'User Account Control' dialogue asking about dcpomatic2_disk_writer.exe?  If so, click 'Yes', then try again.")
318                                 );
319                         m->ShowModal ();
320                         return;
321 #elif defined(DCPOMATIC_OSX)
322                         auto m = make_wx<MessageDialog>(
323                                 this,
324                                 _("DCP-o-matic Disk Writer"),
325                                 _("Did you install the DCP-o-matic Disk Writer.pkg from the .dmg?  Please check and try again.")
326                                 );
327                         m->ShowModal ();
328                         return;
329 #else
330                         LOG_DISK_NC ("Failed to ping writer");
331                         throw CommunicationFailedError ();
332 #endif
333                 }
334
335                 auto const& drive = _drives[_drive->GetSelection()];
336                 if (drive.mounted()) {
337                         auto d = make_wx<TryUnmountDialog>(this, drive.description());
338                         int const r = d->ShowModal ();
339                         if (r != wxID_OK) {
340                                 return;
341                         }
342
343                         LOG_DISK("Sending unmount request to disk writer for %1", drive.as_xml());
344                         if (!_nanomsg.send(DISK_WRITER_UNMOUNT "\n", 2000)) {
345                                 LOG_DISK_NC("Failed to send unmount request.");
346                                 throw CommunicationFailedError ();
347                         }
348                         if (!_nanomsg.send(drive.as_xml(), 2000)) {
349                                 LOG_DISK_NC("Failed to send drive for unmount request.");
350                                 throw CommunicationFailedError ();
351                         }
352                         /* The reply may have to wait for the user to authenticate, so let's wait a while */
353                         auto const reply = DiskWriterBackEndResponse::read_from_nanomsg(_nanomsg, 30000);
354                         if (!reply || reply->type() != DiskWriterBackEndResponse::Type::OK) {
355                                 auto m = make_wx<MessageDialog>(
356                                                 this,
357                                                 _("DCP-o-matic Disk Writer"),
358                                                 wxString::Format(
359                                                         _("The drive %s could not be unmounted.\nClose any application that is using it, then try again. (%s)"),
360                                                         std_to_wx(drive.description()),
361                                                         reply->error_message()
362                                                         )
363                                                 );
364                                 m->ShowModal ();
365                                 return;
366                         }
367                 }
368
369
370                 auto d = make_wx<DriveWipeWarningDialog>(this, _drive->GetString(_drive->GetSelection()));
371                 if (d->ShowModal() != wxID_OK) {
372                         return;
373                 }
374                 if (!d->confirmed()) {
375                         message_dialog(this, _("You did not correctly confirm that you read the warning that was just shown.  Please try again."));
376                         return;
377                 }
378
379                 JobManager::instance()->add(make_shared<CopyToDriveJob>(_dcp_paths, _drives[_drive->GetSelection()], _nanomsg));
380                 setup_sensitivity ();
381         }
382
383         void drive_refresh ()
384         {
385                 int const sel = _drive->GetSelection ();
386                 wxString current;
387                 if (sel != wxNOT_FOUND) {
388                         current = _drive->GetString (sel);
389                 }
390                 _drive->Clear ();
391                 int re_select = wxNOT_FOUND;
392                 int j = 0;
393                 _drives = Drive::get ();
394                 for (auto i: _drives) {
395                         auto const s = std_to_wx(i.description());
396                         if (s == current) {
397                                 re_select = j;
398                         }
399                         _drive->Append(s);
400                         ++j;
401                 }
402                 _drive->SetSelection (re_select);
403                 setup_sensitivity ();
404         }
405
406         void setup_sensitivity ()
407         {
408                 _copy->Enable (!_dcp_paths.empty() && _drive->GetSelection() != wxNOT_FOUND && !JobManager::instance()->work_to_do());
409         }
410
411         wxChoice* _drive;
412         wxButton* _drive_refresh;
413         wxButton* _copy;
414         JobManagerView* _jobs;
415         std::vector<boost::filesystem::path> _dcp_paths;
416         std::vector<Drive> _drives;
417 #ifndef DCPOMATIC_OSX
418         boost::process::child* _writer;
419 #endif
420         Nanomsg _nanomsg;
421         wxSizer* _sizer;
422 };
423
424
425 static const wxCmdLineEntryDesc command_line_description[] = {
426         { wxCMD_LINE_OPTION, "d", "dcp", "DCP to write", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
427         { wxCMD_LINE_SWITCH, "s", "sure", "skip alpha test warnings", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
428         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
429 };
430
431
432 class App : public wxApp
433 {
434 public:
435         App ()
436                 : _frame (nullptr)
437         {}
438
439         bool OnInit () override
440         {
441                 try {
442                         Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
443                         Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
444
445                         SetAppName (_("DCP-o-matic Disk Writer"));
446
447                         if (!wxApp::OnInit()) {
448                                 return false;
449                         }
450
451 #ifdef DCPOMATIC_LINUX
452                         unsetenv ("UBUNTU_MENUPROXY");
453 #endif
454
455 #ifdef DCPOMATIC_OSX
456                         dcpomatic_sleep_seconds (1);
457                         make_foreground_application ();
458 #endif
459
460                         dcpomatic_setup_path_encoding ();
461
462                         /* Enable i18n; this will create a Config object
463                            to look for a force-configured language.  This Config
464                            object will be wrong, however, because dcpomatic_setup
465                            hasn't yet been called and there aren't any filters etc.
466                            set up yet.
467                         */
468                         dcpomatic_setup_i18n ();
469
470                         /* Set things up, including filters etc.
471                            which will now be internationalised correctly.
472                         */
473                         dcpomatic_setup ();
474
475                         /* Force the configuration to be re-loaded correctly next
476                            time it is needed.
477                         */
478                         Config::drop ();
479
480                         if (!_skip_alpha_check) {
481                                 auto warning = make_wx<DiskWarningDialog>();
482                                 if (warning->ShowModal() != wxID_OK) {
483                                         return false;
484                                 }
485                                 if (!warning->confirmed()) {
486                                         message_dialog(nullptr, _("You did not correctly confirm that you read the warning that was just shown.  DCP-o-matic Disk Writer will close now.  Please try again."));
487                                         return false;
488                                 }
489                         }
490
491                         _frame = new DOMFrame (_("DCP-o-matic Disk Writer"));
492                         SetTopWindow (_frame);
493
494                         _frame->Show ();
495
496                         if (_dcp_to_write) {
497                                 _frame->set_dcp_paths({*_dcp_to_write});
498                         }
499
500                         signal_manager = new wxSignalManager (this);
501                         Bind (wxEVT_IDLE, boost::bind (&App::idle, this, _1));
502                 }
503                 catch (exception& e)
504                 {
505                         error_dialog (0, wxString::Format ("DCP-o-matic could not start."), std_to_wx(e.what()));
506                         return false;
507                 }
508
509                 return true;
510         }
511
512         void OnInitCmdLine (wxCmdLineParser& parser) override
513         {
514                 parser.SetDesc (command_line_description);
515                 parser.SetSwitchChars (wxT ("-"));
516         }
517
518         bool OnCmdLineParsed (wxCmdLineParser& parser) override
519         {
520                 _skip_alpha_check = parser.Found(wxT("sure"));
521
522                 wxString dcp;
523                 if (parser.Found(wxT("dcp"), &dcp)) {
524                         _dcp_to_write = wx_to_std (dcp);
525                 }
526
527                 return true;
528         }
529
530         void config_failed_to_load ()
531         {
532                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
533         }
534
535         void config_warning (string m)
536         {
537                 message_dialog (_frame, std_to_wx(m));
538         }
539
540         void idle (wxIdleEvent& ev)
541         {
542                 signal_manager->ui_idle ();
543                 ev.Skip ();
544         }
545
546         void report_exception ()
547         {
548                 try {
549                         throw;
550                 } catch (FileError& e) {
551                         error_dialog (
552                                 0,
553                                 wxString::Format (
554                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
555                                         std_to_wx (e.what()),
556                                         std_to_wx (e.file().string().c_str ())
557                                         )
558                                 );
559                 } catch (exception& e) {
560                         error_dialog (
561                                 0,
562                                 wxString::Format (
563                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
564                                         std_to_wx (e.what ())
565                                         )
566                                 );
567                 } catch (...) {
568                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
569                 }
570         }
571
572         bool OnExceptionInMainLoop () override
573         {
574                 report_exception ();
575                 /* This will terminate the program */
576                 return false;
577         }
578
579         void OnUnhandledException () override
580         {
581                 report_exception ();
582         }
583
584         DOMFrame* _frame;
585         bool _skip_alpha_check = false;
586         boost::optional<boost::filesystem::path> _dcp_to_write;
587 };
588
589 IMPLEMENT_APP (App)