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