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