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