Merge remote-tracking branch 'origin/main' into v2.17.x
[dcpomatic.git] / src / lib / cross_osx.cc
1 /*
2     Copyright (C) 2012-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 "cross.h"
23 #include "compose.hpp"
24 #include "log.h"
25 #include "dcpomatic_log.h"
26 #include "config.h"
27 #include "exceptions.h"
28 #include <dcp/filesystem.h>
29 #include <dcp/raw_convert.h>
30 #include <glib.h>
31 #include <boost/algorithm/string.hpp>
32 #include <boost/regex.hpp>
33 #if BOOST_VERSION >= 106100
34 #include <boost/dll/runtime_symbol_info.hpp>
35 #endif
36 #include <ApplicationServices/ApplicationServices.h>
37 #include <sys/sysctl.h>
38 #include <mach-o/dyld.h>
39 #include <IOKit/pwr_mgt/IOPMLib.h>
40 #include <IOKit/storage/IOMedia.h>
41 #include <DiskArbitration/DADisk.h>
42 #include <DiskArbitration/DiskArbitration.h>
43 #include <CoreFoundation/CFURL.h>
44 #include <sys/types.h>
45 #include <ifaddrs.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48 #include <fstream>
49 #include <cstring>
50
51 #include "i18n.h"
52
53
54 using std::pair;
55 using std::list;
56 using std::ifstream;
57 using std::string;
58 using std::make_pair;
59 using std::vector;
60 using std::cerr;
61 using std::cout;
62 using std::runtime_error;
63 using std::map;
64 using std::shared_ptr;
65 using boost::optional;
66 using std::function;
67
68
69 /** @return A string of CPU information (model name etc.) */
70 string
71 cpu_info ()
72 {
73         string info;
74
75         char buffer[64];
76         size_t N = sizeof (buffer);
77         if (sysctlbyname("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) {
78                 info = buffer;
79         }
80
81         return info;
82 }
83
84
85 boost::filesystem::path
86 directory_containing_executable ()
87 {
88         return dcp::filesystem::canonical(boost::dll::program_location()).parent_path();
89 }
90
91
92 boost::filesystem::path
93 resources_path ()
94 {
95         return directory_containing_executable().parent_path() / "Resources";
96 }
97
98
99 boost::filesystem::path
100 libdcp_resources_path ()
101 {
102         return resources_path();
103 }
104
105
106 void
107 run_ffprobe(boost::filesystem::path content, boost::filesystem::path out, bool err, string args)
108 {
109         auto path = directory_containing_executable () / "ffprobe";
110         if (!dcp::filesystem::exists(path)) {
111                 /* This is a hack but we need ffprobe during tests */
112                 path = "/Users/ci/workspace/bin/ffprobe";
113         }
114         string const redirect = err ? "2>" : ">";
115
116         auto const ffprobe = String::compose("\"%1\" %2 \"%3\" %4 \"%5\"", path, args.empty() ? " " : args, content.string(), redirect, out.string());
117         LOG_GENERAL (N_("Probing with %1"), ffprobe);
118         system (ffprobe.c_str());
119 }
120
121
122
123 list<pair<string, string>>
124 mount_info ()
125 {
126         return {};
127 }
128
129
130 boost::filesystem::path
131 openssl_path ()
132 {
133         return directory_containing_executable() / "openssl";
134 }
135
136
137 #ifdef DCPOMATIC_DISK
138 /* Note: this isn't actually used at the moment as the disk writer is started as a service */
139 boost::filesystem::path
140 disk_writer_path ()
141 {
142         return directory_containing_executable() / "dcpomatic2_disk_writer";
143 }
144 #endif
145
146
147 void
148 Waker::nudge ()
149 {
150
151 }
152
153
154 Waker::Waker ()
155 {
156         boost::mutex::scoped_lock lm (_mutex);
157         IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
158 }
159
160
161 Waker::~Waker ()
162 {
163         boost::mutex::scoped_lock lm (_mutex);
164         IOPMAssertionRelease (_assertion_id);
165 }
166
167
168 void
169 start_tool (string executable, string app)
170 {
171         auto exe_path = directory_containing_executable();
172         exe_path = exe_path.parent_path(); // Contents
173         exe_path = exe_path.parent_path(); // DCP-o-matic 2.app
174         exe_path = exe_path.parent_path(); // Applications
175         exe_path /= app;
176         exe_path /= "Contents";
177         exe_path /= "MacOS";
178         exe_path /= executable;
179
180         pid_t pid = fork ();
181         if (pid == 0) {
182                 LOG_GENERAL ("start_tool %1 %2 with path %3", executable, app, exe_path.string());
183                 int const r = system (exe_path.string().c_str());
184                 exit (WEXITSTATUS (r));
185         } else if (pid == -1) {
186                 LOG_ERROR_NC("Fork failed in start_tool");
187         }
188 }
189
190
191 void
192 start_batch_converter ()
193 {
194         start_tool ("dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
195 }
196
197
198 void
199 start_player ()
200 {
201         start_tool ("dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
202 }
203
204
205 static optional<string>
206 get_vendor (CFDictionaryRef& description)
207 {
208         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceVendorKey);
209         if (!str) {
210                 return {};
211         }
212
213         auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
214         if (!c_str) {
215                 return {};
216         }
217
218         string s (c_str);
219         boost::algorithm::trim (s);
220         return s;
221 }
222
223
224 static optional<string>
225 get_model (CFDictionaryRef& description)
226 {
227         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey);
228         if (!str) {
229                 return {};
230         }
231
232         auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
233         if (!c_str) {
234                 return {};
235         }
236
237         string s (c_str);
238         boost::algorithm::trim (s);
239         return s;
240 }
241
242
243 static optional<boost::filesystem::path>
244 mount_point (CFDictionaryRef& description)
245 {
246         auto volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey);
247         if (!volume_path_key) {
248                 return {};
249         }
250
251         char mount_path_buffer[1024];
252         if (!CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer))) {
253                 return {};
254         }
255         return boost::filesystem::path(mount_path_buffer);
256 }
257
258
259 static bool
260 get_bool(CFDictionaryRef& description, void const* key)
261 {
262         auto value = CFDictionaryGetValue(description, key);
263         if (!value) {
264                 return false;
265         }
266
267         return CFBooleanGetValue(reinterpret_cast<CFBooleanRef>(value));
268 }
269
270
271 static void
272 disk_appeared (DADiskRef disk, void* context)
273 {
274         auto bsd_name = DADiskGetBSDName (disk);
275         if (!bsd_name) {
276                 LOG_DISK_NC("Disk with no BSDName appeared");
277                 return;
278         }
279         LOG_DISK("%1 appeared", bsd_name);
280
281         OSXDisk this_disk;
282
283         this_disk.device = string("/dev/") + bsd_name;
284         LOG_DISK("Device is %1", this_disk.device);
285
286         CFDictionaryRef description = DADiskCopyDescription (disk);
287
288         this_disk.vendor = get_vendor (description);
289         this_disk.model = get_model (description);
290         LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]"));
291
292         auto mp = mount_point (description);
293         if (mp) {
294                 this_disk.mount_points.push_back (*mp);
295         }
296
297         auto media_size_cstr = CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey);
298         if (!media_size_cstr) {
299                 LOG_DISK_NC("Could not read media size");
300                 return;
301         }
302
303         this_disk.system = get_bool(description, kDADiskDescriptionDeviceInternalKey) && !get_bool(description, kDADiskDescriptionMediaRemovableKey);
304         this_disk.writeable = get_bool(description, kDADiskDescriptionMediaWritableKey);
305         this_disk.partition = string(bsd_name).find("s", 5) != std::string::npos;
306
307         LOG_DISK(
308                 "%1 %2 %3 %4 mounted at %5",
309                 bsd_name,
310                 this_disk.system ? "system" : "non-system",
311                 this_disk.writeable ? "writeable" : "read-only",
312                 this_disk.partition ? "partition" : "drive",
313                 mp ? mp->string() : "[nowhere]"
314                 );
315
316         CFNumberGetValue ((CFNumberRef) media_size_cstr, kCFNumberLongType, &this_disk.size);
317         CFRelease (description);
318
319         reinterpret_cast<vector<OSXDisk>*>(context)->push_back(this_disk);
320 }
321
322
323 vector<Drive>
324 Drive::get ()
325 {
326         using namespace boost::algorithm;
327         vector<OSXDisk> disks;
328
329         LOG_DISK_NC("Drive::get() starts");
330
331         auto session = DASessionCreate(kCFAllocatorDefault);
332         if (!session) {
333                 return {};
334         }
335
336         LOG_DISK_NC("Drive::get() has session");
337
338         DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks);
339         auto run_loop = CFRunLoopGetCurrent ();
340         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
341         CFRunLoopStop (run_loop);
342         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0);
343         DAUnregisterCallback(session, (void *) disk_appeared, &disks);
344         CFRelease(session);
345
346         vector<Drive> drives;
347         for (auto const& disk: disks) {
348                 if (!disk.system && !disk.partition && disk.writeable) {
349                         drives.push_back({disk.device, disk.mount_points, disk.size, disk.vendor, disk.model});
350                 }
351         }
352
353         LOG_DISK("Drive::get() found %1 drives:", drives.size());
354         for (auto const& drive: drives) {
355                 LOG_DISK("%1 %2 mounted=%3", drive.description(), drive.device(), drive.mounted() ? "yes" : "no");
356         }
357
358         return drives;
359 }
360
361
362 boost::filesystem::path
363 config_path (optional<string> version)
364 {
365         boost::filesystem::path p;
366         p /= g_get_home_dir ();
367         p /= "Library";
368         p /= "Preferences";
369         p /= "com.dcpomatic";
370         p /= "2";
371         if (version) {
372                 p /= *version;
373         }
374         return p;
375 }
376
377
378 struct UnmountState
379 {
380         bool success = false;
381         bool callback = false;
382 };
383
384
385 void done_callback(DADiskRef, DADissenterRef dissenter, void* context)
386 {
387         LOG_DISK_NC("Unmount finished");
388         auto state = reinterpret_cast<UnmountState*>(context);
389         state->callback = true;
390         if (dissenter) {
391                 LOG_DISK("Error: %1", DADissenterGetStatus(dissenter));
392         } else {
393                 LOG_DISK_NC("Successful");
394                 state->success = true;
395         }
396 }
397
398
399 bool
400 Drive::unmount ()
401 {
402         LOG_DISK_NC("Unmount operation started");
403
404         auto session = DASessionCreate(kCFAllocatorDefault);
405         if (!session) {
406                 return false;
407         }
408
409         auto disk = DADiskCreateFromBSDName(kCFAllocatorDefault, session, _device.c_str());
410         if (!disk) {
411                 return false;
412         }
413         LOG_DISK("Requesting unmount of %1 from %2", _device, thread_id());
414         UnmountState state;
415         DADiskUnmount(disk, kDADiskUnmountOptionWhole, &done_callback, &state);
416         CFRelease (disk);
417
418         CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
419         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
420         CFRunLoopStop (run_loop);
421         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 5, 0);
422         CFRelease(session);
423
424         if (!state.callback) {
425                 LOG_DISK_NC("End of unmount: timeout");
426         } else {
427                 LOG_DISK("End of unmount: %1", state.success ? "success" : "failure");
428         }
429         return state.success;
430 }
431
432
433 void
434 disk_write_finished ()
435 {
436
437 }
438
439
440 void
441 make_foreground_application ()
442 {
443         ProcessSerialNumber serial;
444 LIBDCP_DISABLE_WARNINGS
445         GetCurrentProcess (&serial);
446 LIBDCP_ENABLE_WARNINGS
447         TransformProcessType (&serial, kProcessTransformToForegroundApplication);
448 }
449
450
451 bool
452 show_in_file_manager (boost::filesystem::path, boost::filesystem::path select)
453 {
454         int r = system (String::compose("open -R \"%1\"", select.string()).c_str());
455         return static_cast<bool>(WEXITSTATUS(r));
456 }
457