Work around strange build error on Ubuntu 18.04
[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/copy_to_drive_job.h"
33 #include "lib/cross.h"
34 #include "lib/dcpomatic_log.h"
35 #include "lib/disk_writer_messages.h"
36 #include "lib/file_log.h"
37 #include "lib/job_manager.h"
38 #include "lib/signal_manager.h"
39 #include "lib/util.h"
40 #include "lib/version.h"
41 #include <dcp/warnings.h>
42 #include <wx/cmdline.h>
43 #include <wx/wx.h>
44 LIBDCP_DISABLE_WARNINGS
45 #include <boost/process.hpp>
46 LIBDCP_ENABLE_WARNINGS
47 #ifdef DCPOMATIC_WINDOWS
48 #include <boost/process/windows.hpp>
49 #endif
50 #ifdef DCPOMATIC_OSX
51 #include <notify.h>
52 #endif
53
54
55 using std::cerr;
56 using std::cout;
57 using std::exception;
58 using std::make_shared;
59 using std::shared_ptr;
60 using std::string;
61 using std::vector;
62 using boost::optional;
63 #if BOOST_VERSION >= 106100
64 using namespace boost::placeholders;
65 #endif
66
67
68 #ifdef DCPOMATIC_OSX
69 enum {
70         ID_tools_uninstall = 1,
71 };
72 #endif
73
74
75 class DirDialogWrapper : public wxDirDialog
76 {
77 public:
78         DirDialogWrapper (wxWindow* parent)
79                 : wxDirDialog (parent, _("Choose a DCP folder"), wxT(""), wxDD_DIR_MUST_EXIST)
80         {
81
82         }
83
84         boost::optional<boost::filesystem::path> get () const
85         {
86                 auto const dcp = boost::filesystem::path(wx_to_std(GetPath()));
87                 if (!boost::filesystem::exists(dcp / "ASSETMAP") && !boost::filesystem::exists(dcp / "ASSETMAP.xml")) {
88                         error_dialog (nullptr, _("No ASSETMAP or ASSETMAP.xml found in this folder.  Please choose a DCP folder."));
89                         return {};
90                 }
91
92                 return dcp;
93         }
94
95         void set (boost::filesystem::path)
96         {
97                 /* Not used */
98         }
99 };
100
101
102 class DOMFrame : public wxFrame
103 {
104 public:
105         explicit DOMFrame (wxString const & title)
106                 : wxFrame (nullptr, wxID_ANY, title)
107                 , _nanomsg (true)
108                 , _sizer (new wxBoxSizer(wxVERTICAL))
109         {
110 #ifdef DCPOMATIC_OSX
111                 auto bar = new wxMenuBar;
112                 auto tools = new wxMenu;
113                 tools->Append(ID_tools_uninstall, _("Uninstall..."));
114                 bar->Append(tools, _("Tools"));
115                 SetMenuBar (bar);
116                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::uninstall, this), ID_tools_uninstall);
117 #endif
118
119                 /* Use a panel as the only child of the Frame so that we avoid
120                    the dark-grey background on Windows.
121                 */
122                 auto overall_panel = new wxPanel (this);
123                 auto s = new wxBoxSizer (wxHORIZONTAL);
124                 s->Add (overall_panel, 1, wxEXPAND);
125                 SetSizer (s);
126
127                 auto grid = new wxGridBagSizer (DCPOMATIC_SIZER_X_GAP, DCPOMATIC_SIZER_Y_GAP);
128
129                 int r = 0;
130                 add_label_to_sizer (grid, overall_panel, _("DCP"), true, wxGBPosition(r, 0));
131                 auto dcp_sizer = new wxBoxSizer (wxHORIZONTAL);
132                 auto dcps = new EditableList<boost::filesystem::path, DirDialogWrapper>(
133                         overall_panel,
134                         { EditableListColumn(_("DCP"), 300, true) },
135                         boost::bind(&DOMFrame::dcp_paths, this),
136                         boost::bind(&DOMFrame::set_dcp_paths, this, _1),
137                         [](boost::filesystem::path p, int) { return p.filename().string(); },
138                         EditableListTitle::INVISIBLE,
139                         EditableListButton::NEW | EditableListButton::REMOVE
140                         );
141
142                 dcp_sizer->Add(dcps, 1, wxALIGN_CENTER_VERTICAL, DCPOMATIC_SIZER_X_GAP);
143                 grid->Add(dcp_sizer, wxGBPosition(r, 1), wxDefaultSpan, wxEXPAND);
144                 ++r;
145
146                 add_label_to_sizer (grid, overall_panel, _("Drive"), true, wxGBPosition(r, 0));
147                 auto drive_sizer = new wxBoxSizer (wxHORIZONTAL);
148                 _drive = new wxChoice (overall_panel, wxID_ANY);
149                 drive_sizer->Add (_drive, 1, wxALIGN_CENTER_VERTICAL | wxRIGHT, DCPOMATIC_SIZER_X_GAP);
150                 _drive_refresh = new wxButton (overall_panel, wxID_ANY, _("Refresh"));
151                 drive_sizer->Add (_drive_refresh, 0);
152                 grid->Add (drive_sizer, wxGBPosition(r, 1), wxDefaultSpan, wxEXPAND);
153                 ++r;
154
155                 _jobs = new JobManagerView (overall_panel, false);
156                 grid->Add (_jobs, wxGBPosition(r, 0), wxGBSpan(6, 2), wxEXPAND);
157                 r += 6;
158
159                 _copy = new wxButton (overall_panel, wxID_ANY, _("Copy DCP"));
160                 grid->Add (_copy, wxGBPosition(r, 0), wxGBSpan(1, 2), wxEXPAND);
161                 ++r;
162
163                 grid->AddGrowableCol (1);
164
165                 _copy->Bind (wxEVT_BUTTON, boost::bind(&DOMFrame::copy, this));
166                 _drive->Bind (wxEVT_CHOICE, boost::bind(&DOMFrame::setup_sensitivity, this));
167                 _drive_refresh->Bind (wxEVT_BUTTON, boost::bind(&DOMFrame::drive_refresh, this));
168
169                 _sizer->Add (grid, 1, wxALL | wxEXPAND, DCPOMATIC_DIALOG_BORDER);
170                 overall_panel->SetSizer (_sizer);
171                 Fit ();
172                 SetSize (1024, GetSize().GetHeight() + 32);
173
174                 /* XXX: this is a hack, but I expect we'll need logs and I'm not sure if there's
175                  * a better place to put them.
176                  */
177                 dcpomatic_log = make_shared<FileLog>(State::write_path("disk.log"));
178                 dcpomatic_log->set_types (dcpomatic_log->types() | LogEntry::TYPE_DISK);
179                 LOG_DISK("dcpomatic_disk %1 started", dcpomatic_git_commit);
180
181                 drive_refresh ();
182
183                 Bind (wxEVT_SIZE, boost::bind(&DOMFrame::sized, this, _1));
184                 Bind (wxEVT_CLOSE_WINDOW, boost::bind(&DOMFrame::close, this, _1));
185
186                 JobManager::instance()->ActiveJobsChanged.connect(boost::bind(&DOMFrame::setup_sensitivity, this));
187
188 #ifdef DCPOMATIC_WINDOWS
189                 /* We must use ::shell here, it seems, to avoid error code 740 (related to privilege escalation) */
190                 LOG_DISK("Starting writer process %1", disk_writer_path().string());
191                 _writer = new boost::process::child (disk_writer_path(), boost::process::shell, boost::process::windows::hide);
192 #endif
193
194 #ifdef DCPOMATIC_LINUX
195                 if (getenv("DCPOMATIC_NO_START_WRITER")) {
196                         LOG_DISK_NC("Not starting writer process as DCPOMATIC_NO_START_WRITER is set");
197                 } else {
198                         LOG_DISK("Starting writer process %1", disk_writer_path().string());
199                         _writer = new boost::process::child (disk_writer_path());
200                 }
201 #endif
202
203 #ifdef DCPOMATIC_OSX
204                 LOG_DISK_NC("Sending notification to writer daemon");
205                 notify_post ("com.dcpomatic.disk.writer.start");
206 #endif
207         }
208
209         ~DOMFrame ()
210         {
211                 _nanomsg.send(DISK_WRITER_QUIT "\n", 2000);
212                 /* This seems really horrible but it's suggested by the examples on nanomsg.org, so...
213                  * Without this the quit is not received (at least sometimes) causing #2018.
214                  */
215                 dcpomatic_sleep_seconds (1);
216         }
217
218         void set_dcp_paths (vector<boost::filesystem::path> dcps)
219         {
220                 _dcp_paths = dcps;
221                 setup_sensitivity();
222         }
223
224 private:
225         vector<boost::filesystem::path> dcp_paths() const
226         {
227                 return _dcp_paths;
228         }
229
230         void sized (wxSizeEvent& ev)
231         {
232                 _sizer->Layout ();
233                 ev.Skip ();
234         }
235
236
237 #ifdef DCPOMATIC_OSX
238         void uninstall()
239         {
240                 system(String::compose("osascript \"%1/uninstall_disk.applescript\"", resources_path().string()).c_str());
241         }
242 #endif
243
244
245         bool should_close ()
246         {
247                 if (!JobManager::instance()->work_to_do()) {
248                         return true;
249                 }
250
251                 auto d = new wxMessageDialog (
252                         0,
253                         _("There are unfinished jobs; are you sure you want to quit?"),
254                         _("Unfinished jobs"),
255                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
256                         );
257
258                 bool const r = d->ShowModal() == wxID_YES;
259                 d->Destroy ();
260                 return r;
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 = _nanomsg.receive (1000);
289                                 if (reply && *reply == DISK_WRITER_PONG) {
290                                         return true;
291                                 } else if (reply) {
292                                         LOG_DISK("Unexpected response %1 to ping received (attempt %2)", *reply, 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 = new 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                         m->Destroy ();
320                         return;
321 #elif defined(DCPOMATIC_OSX)
322                         auto m = new 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                         m->Destroy ();
329                         return;
330 #else
331                         LOG_DISK_NC ("Failed to ping writer");
332                         throw CommunicationFailedError ();
333 #endif
334                 }
335
336                 auto const& drive = _drives[_drive->GetSelection()];
337                 if (drive.mounted()) {
338                         auto d = new TryUnmountDialog(this, drive.description());
339                         int const r = d->ShowModal ();
340                         d->Destroy ();
341                         if (r != wxID_OK) {
342                                 return;
343                         }
344
345                         LOG_DISK("Sending unmount request to disk writer for %1", drive.as_xml());
346                         if (!_nanomsg.send(DISK_WRITER_UNMOUNT "\n", 2000)) {
347                                 LOG_DISK_NC("Failed to send unmount request.");
348                                 throw CommunicationFailedError ();
349                         }
350                         if (!_nanomsg.send(drive.as_xml(), 2000)) {
351                                 LOG_DISK_NC("Failed to send drive for unmount request.");
352                                 throw CommunicationFailedError ();
353                         }
354                         /* The reply may have to wait for the user to authenticate, so let's wait a while */
355                         auto reply = _nanomsg.receive (30000);
356                         if (!reply || *reply != DISK_WRITER_OK) {
357                                 auto * m = new MessageDialog (
358                                                 this,
359                                                 _("DCP-o-matic Disk Writer"),
360                                                 wxString::Format(_("The drive %s could not be unmounted.\nClose any application that is using it, then try again."), std_to_wx(drive.description()))
361                                                 );
362                                 m->ShowModal ();
363                                 m->Destroy ();
364                                 return;
365                         }
366                 }
367
368
369                 auto * d = new DriveWipeWarningDialog (this, _drive->GetString(_drive->GetSelection()));
370                 int const r = d->ShowModal ();
371                 bool ok = r == wxID_OK && d->confirmed();
372                 d->Destroy ();
373
374                 if (!ok) {
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 = new DiskWarningDialog ();
481                                 warning->ShowModal ();
482                                 if (!warning->confirmed()) {
483                                         return false;
484                                 }
485                                 warning->Destroy ();
486                         }
487
488                         _frame = new DOMFrame (_("DCP-o-matic Disk Writer"));
489                         SetTopWindow (_frame);
490
491                         _frame->Show ();
492
493                         if (_dcp_to_write) {
494                                 _frame->set_dcp_paths({*_dcp_to_write});
495                         }
496
497                         signal_manager = new wxSignalManager (this);
498                         Bind (wxEVT_IDLE, boost::bind (&App::idle, this, _1));
499                 }
500                 catch (exception& e)
501                 {
502                         error_dialog (0, wxString::Format ("DCP-o-matic could not start."), std_to_wx(e.what()));
503                         return false;
504                 }
505
506                 return true;
507         }
508
509         void OnInitCmdLine (wxCmdLineParser& parser) override
510         {
511                 parser.SetDesc (command_line_description);
512                 parser.SetSwitchChars (wxT ("-"));
513         }
514
515         bool OnCmdLineParsed (wxCmdLineParser& parser) override
516         {
517                 _skip_alpha_check = parser.Found(wxT("sure"));
518
519                 wxString dcp;
520                 if (parser.Found(wxT("dcp"), &dcp)) {
521                         _dcp_to_write = wx_to_std (dcp);
522                 }
523
524                 return true;
525         }
526
527         void config_failed_to_load ()
528         {
529                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
530         }
531
532         void config_warning (string m)
533         {
534                 message_dialog (_frame, std_to_wx(m));
535         }
536
537         void idle (wxIdleEvent& ev)
538         {
539                 signal_manager->ui_idle ();
540                 ev.Skip ();
541         }
542
543         void report_exception ()
544         {
545                 try {
546                         throw;
547                 } catch (FileError& e) {
548                         error_dialog (
549                                 0,
550                                 wxString::Format (
551                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
552                                         std_to_wx (e.what()),
553                                         std_to_wx (e.file().string().c_str ())
554                                         )
555                                 );
556                 } catch (exception& e) {
557                         error_dialog (
558                                 0,
559                                 wxString::Format (
560                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
561                                         std_to_wx (e.what ())
562                                         )
563                                 );
564                 } catch (...) {
565                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
566                 }
567         }
568
569         bool OnExceptionInMainLoop () override
570         {
571                 report_exception ();
572                 /* This will terminate the program */
573                 return false;
574         }
575
576         void OnUnhandledException () override
577         {
578                 report_exception ();
579         }
580
581         DOMFrame* _frame;
582         bool _skip_alpha_check = false;
583         boost::optional<boost::filesystem::path> _dcp_to_write;
584 };
585
586 IMPLEMENT_APP (App)