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