1
0

platform-osx.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. /******************************************************************************
  2. Copyright (C) 2013 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <sstream>
  15. #include <dlfcn.h>
  16. #include <util/base.h>
  17. #include <util/threading.h>
  18. #include <obs-config.h>
  19. #include "platform.hpp"
  20. #include "obs-app.hpp"
  21. #include <unistd.h>
  22. #import <AppKit/AppKit.h>
  23. #import <CoreFoundation/CoreFoundation.h>
  24. #import <AVFoundation/AVFoundation.h>
  25. #import <ApplicationServices/ApplicationServices.h>
  26. using namespace std;
  27. bool isInBundle()
  28. {
  29. NSRunningApplication *app = [NSRunningApplication currentApplication];
  30. return [app bundleIdentifier] != nil;
  31. }
  32. bool GetDataFilePath(const char *data, string &output)
  33. {
  34. NSRunningApplication *app = [NSRunningApplication currentApplication];
  35. NSURL *bundleURL = [app bundleURL];
  36. NSString *path = [NSString
  37. stringWithFormat:@"Contents/Resources/%@",
  38. [NSString stringWithUTF8String:data]];
  39. NSURL *dataURL = [bundleURL URLByAppendingPathComponent:path];
  40. output = [[dataURL path] UTF8String];
  41. return !access(output.c_str(), R_OK);
  42. }
  43. void CheckIfAlreadyRunning(bool &already_running)
  44. {
  45. try {
  46. NSBundle *bundle = [NSBundle mainBundle];
  47. if (!bundle)
  48. throw "Could not find main bundle";
  49. NSString *bundleID = [bundle bundleIdentifier];
  50. if (!bundleID)
  51. throw "Could not find bundle identifier";
  52. int app_count =
  53. [NSRunningApplication
  54. runningApplicationsWithBundleIdentifier:bundleID]
  55. .count;
  56. already_running = app_count > 1;
  57. } catch (const char *error) {
  58. blog(LOG_ERROR, "CheckIfAlreadyRunning: %s", error);
  59. }
  60. }
  61. string GetDefaultVideoSavePath()
  62. {
  63. NSFileManager *fm = [NSFileManager defaultManager];
  64. NSURL *url = [fm URLForDirectory:NSMoviesDirectory
  65. inDomain:NSUserDomainMask
  66. appropriateForURL:nil
  67. create:true
  68. error:nil];
  69. if (!url)
  70. return getenv("HOME");
  71. return url.path.fileSystemRepresentation;
  72. }
  73. vector<string> GetPreferredLocales()
  74. {
  75. NSArray *preferred = [NSLocale preferredLanguages];
  76. auto locales = GetLocaleNames();
  77. auto lang_to_locale = [&locales](string lang) -> string {
  78. string lang_match = "";
  79. for (const auto &locale : locales) {
  80. if (locale.first == lang.substr(0, locale.first.size()))
  81. return locale.first;
  82. if (!lang_match.size() &&
  83. locale.first.substr(0, 2) == lang.substr(0, 2))
  84. lang_match = locale.first;
  85. }
  86. return lang_match;
  87. };
  88. vector<string> result;
  89. result.reserve(preferred.count);
  90. for (NSString *lang in preferred) {
  91. string locale = lang_to_locale(lang.UTF8String);
  92. if (!locale.size())
  93. continue;
  94. if (find(begin(result), end(result), locale) != end(result))
  95. continue;
  96. result.emplace_back(locale);
  97. }
  98. return result;
  99. }
  100. bool IsAlwaysOnTop(QWidget *window)
  101. {
  102. return (window->windowFlags() & Qt::WindowStaysOnTopHint) != 0;
  103. }
  104. void disableColorSpaceConversion(QWidget *window)
  105. {
  106. NSView *view =
  107. (__bridge NSView *)reinterpret_cast<void *>(window->winId());
  108. view.window.colorSpace = NSColorSpace.sRGBColorSpace;
  109. }
  110. void SetAlwaysOnTop(QWidget *window, bool enable)
  111. {
  112. Qt::WindowFlags flags = window->windowFlags();
  113. if (enable) {
  114. /* Force the level of the window high so it sits on top of
  115. * full-screen applications like Keynote */
  116. NSView *nsv = (__bridge NSView *)reinterpret_cast<void *>(
  117. window->winId());
  118. NSWindow *nsw = nsv.window;
  119. [nsw setLevel:1024];
  120. flags |= Qt::WindowStaysOnTopHint;
  121. } else {
  122. flags &= ~Qt::WindowStaysOnTopHint;
  123. }
  124. window->setWindowFlags(flags);
  125. window->show();
  126. }
  127. bool SetDisplayAffinitySupported(void)
  128. {
  129. // Not implemented yet
  130. return false;
  131. }
  132. typedef void (*set_int_t)(int);
  133. void EnableOSXVSync(bool enable)
  134. {
  135. static bool initialized = false;
  136. static bool valid = false;
  137. static set_int_t set_debug_options = nullptr;
  138. static set_int_t deferred_updates = nullptr;
  139. if (!initialized) {
  140. void *quartzCore = dlopen("/System/Library/Frameworks/"
  141. "QuartzCore.framework/QuartzCore",
  142. RTLD_LAZY);
  143. if (quartzCore) {
  144. set_debug_options = (set_int_t)dlsym(
  145. quartzCore, "CGSSetDebugOptions");
  146. deferred_updates = (set_int_t)dlsym(
  147. quartzCore, "CGSDeferredUpdates");
  148. valid = set_debug_options && deferred_updates;
  149. }
  150. initialized = true;
  151. }
  152. if (valid) {
  153. set_debug_options(enable ? 0 : 0x08000000);
  154. deferred_updates(enable ? 1 : 0);
  155. }
  156. }
  157. void EnableOSXDockIcon(bool enable)
  158. {
  159. if (enable)
  160. [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
  161. else
  162. [NSApp setActivationPolicy:
  163. NSApplicationActivationPolicyProhibited];
  164. }
  165. @interface DockView : NSView {
  166. @private
  167. QIcon icon;
  168. }
  169. @end
  170. @implementation DockView
  171. - (id)initWithIcon:(QIcon)icon
  172. {
  173. self = [super init];
  174. self->icon = icon;
  175. return self;
  176. }
  177. - (void)drawRect:(NSRect)dirtyRect
  178. {
  179. CGSize size = dirtyRect.size;
  180. /* Draw regular app icon */
  181. NSImage *appIcon = [[NSWorkspace sharedWorkspace]
  182. iconForFile:[[NSBundle mainBundle] bundlePath]];
  183. [appIcon drawInRect:CGRectMake(0, 0, size.width, size.height)];
  184. /* Draw small icon on top */
  185. float iconSize = 0.45;
  186. CGImageRef image =
  187. icon.pixmap(size.width, size.height).toImage().toCGImage();
  188. CGContextRef context = [[NSGraphicsContext currentContext] CGContext];
  189. CGContextDrawImage(context,
  190. CGRectMake(size.width * (1 - iconSize), 0,
  191. size.width * iconSize,
  192. size.height * iconSize),
  193. image);
  194. CGImageRelease(image);
  195. }
  196. @end
  197. MacPermissionStatus CheckPermissionWithPrompt(MacPermissionType type,
  198. bool prompt_for_permission)
  199. {
  200. __block MacPermissionStatus permissionResponse =
  201. kPermissionNotDetermined;
  202. switch (type) {
  203. case kAudioDeviceAccess: {
  204. AVAuthorizationStatus audioStatus = [AVCaptureDevice
  205. authorizationStatusForMediaType:AVMediaTypeAudio];
  206. if (audioStatus == AVAuthorizationStatusNotDetermined &&
  207. prompt_for_permission) {
  208. os_event_t *block_finished;
  209. os_event_init(&block_finished, OS_EVENT_TYPE_MANUAL);
  210. [AVCaptureDevice
  211. requestAccessForMediaType:AVMediaTypeAudio
  212. completionHandler:^(
  213. BOOL granted
  214. __attribute((unused))) {
  215. os_event_signal(block_finished);
  216. }];
  217. os_event_wait(block_finished);
  218. os_event_destroy(block_finished);
  219. audioStatus = [AVCaptureDevice
  220. authorizationStatusForMediaType:AVMediaTypeAudio];
  221. }
  222. permissionResponse = (MacPermissionStatus)audioStatus;
  223. blog(LOG_INFO, "[macOS] Permission for audio device access %s.",
  224. permissionResponse == kPermissionAuthorized ? "granted"
  225. : "denied");
  226. break;
  227. }
  228. case kVideoDeviceAccess: {
  229. AVAuthorizationStatus videoStatus = [AVCaptureDevice
  230. authorizationStatusForMediaType:AVMediaTypeVideo];
  231. if (videoStatus == AVAuthorizationStatusNotDetermined &&
  232. prompt_for_permission) {
  233. os_event_t *block_finished;
  234. os_event_init(&block_finished, OS_EVENT_TYPE_MANUAL);
  235. [AVCaptureDevice
  236. requestAccessForMediaType:AVMediaTypeVideo
  237. completionHandler:^(
  238. BOOL granted
  239. __attribute((unused))) {
  240. os_event_signal(block_finished);
  241. }];
  242. os_event_wait(block_finished);
  243. os_event_destroy(block_finished);
  244. videoStatus = [AVCaptureDevice
  245. authorizationStatusForMediaType:AVMediaTypeVideo];
  246. }
  247. permissionResponse = (MacPermissionStatus)videoStatus;
  248. blog(LOG_INFO, "[macOS] Permission for video device access %s.",
  249. permissionResponse == kPermissionAuthorized ? "granted"
  250. : "denied");
  251. break;
  252. }
  253. case kScreenCapture: {
  254. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 110000
  255. if (@available(macOS 11.0, *)) {
  256. permissionResponse = (CGPreflightScreenCaptureAccess()
  257. ? kPermissionAuthorized
  258. : kPermissionDenied);
  259. if (permissionResponse != kPermissionAuthorized &&
  260. prompt_for_permission) {
  261. permissionResponse =
  262. (CGRequestScreenCaptureAccess()
  263. ? kPermissionAuthorized
  264. : kPermissionDenied);
  265. }
  266. } else {
  267. #else
  268. {
  269. #endif
  270. CGDisplayStreamRef stream = CGDisplayStreamCreate(
  271. CGMainDisplayID(), 1, 1,
  272. kCVPixelFormatType_32BGRA, nil, nil);
  273. if (stream) {
  274. permissionResponse = kPermissionAuthorized;
  275. CFRelease(stream);
  276. if (prompt_for_permission) {
  277. }
  278. } else {
  279. permissionResponse = kPermissionDenied;
  280. }
  281. }
  282. blog(LOG_INFO, "[macOS] Permission for screen capture %s.",
  283. permissionResponse == kPermissionAuthorized ? "granted"
  284. : "denied");
  285. break;
  286. }
  287. case kAccessibility: {
  288. permissionResponse = (AXIsProcessTrusted()
  289. ? kPermissionAuthorized
  290. : kPermissionDenied);
  291. if (permissionResponse != kPermissionAuthorized &&
  292. prompt_for_permission) {
  293. NSDictionary *options = @{
  294. (__bridge id)kAXTrustedCheckOptionPrompt: @YES
  295. };
  296. permissionResponse = (AXIsProcessTrustedWithOptions(
  297. (CFDictionaryRef)options)
  298. ? kPermissionAuthorized
  299. : kPermissionDenied);
  300. }
  301. blog(LOG_INFO, "[macOS] Permission for accessibility %s.",
  302. permissionResponse == kPermissionAuthorized ? "granted"
  303. : "denied");
  304. break;
  305. }
  306. }
  307. return permissionResponse;
  308. }
  309. void OpenMacOSPrivacyPreferences(const char *tab)
  310. {
  311. NSURL *url = [NSURL
  312. URLWithString:
  313. [NSString
  314. stringWithFormat:
  315. @"x-apple.systempreferences:com.apple.preference.security?Privacy_%s",
  316. tab]];
  317. [[NSWorkspace sharedWorkspace] openURL:url];
  318. }
  319. void TaskbarOverlayInit() {}
  320. void TaskbarOverlaySetStatus(TaskbarOverlayStatus status)
  321. {
  322. QIcon icon;
  323. if (status == TaskbarOverlayStatusActive)
  324. icon = QIcon::fromTheme("obs-active",
  325. QIcon(":/res/images/active_mac.png"));
  326. else if (status == TaskbarOverlayStatusPaused)
  327. icon = QIcon::fromTheme("obs-paused",
  328. QIcon(":/res/images/paused_mac.png"));
  329. NSDockTile *tile = [NSApp dockTile];
  330. [tile setContentView:[[DockView alloc] initWithIcon:icon]];
  331. [tile display];
  332. }
  333. /*
  334. * This custom NSApplication subclass makes the app compatible with CEF. Qt
  335. * also has an NSApplication subclass, but it doesn't conflict thanks to Qt
  336. * using arcane magic to hook into the NSApplication superclass itself if the
  337. * program has its own NSApplication subclass.
  338. */
  339. @protocol CrAppProtocol
  340. - (BOOL)isHandlingSendEvent;
  341. @end
  342. @interface OBSApplication : NSApplication <CrAppProtocol>
  343. @property (nonatomic, getter=isHandlingSendEvent) BOOL handlingSendEvent;
  344. @end
  345. @implementation OBSApplication
  346. - (void)sendEvent:(NSEvent *)event
  347. {
  348. _handlingSendEvent = YES;
  349. [super sendEvent:event];
  350. _handlingSendEvent = NO;
  351. }
  352. @end
  353. void InstallNSThreadLocks()
  354. {
  355. [[NSThread new] start];
  356. if ([NSThread isMultiThreaded] != 1) {
  357. abort();
  358. }
  359. }
  360. void InstallNSApplicationSubclass()
  361. {
  362. [OBSApplication sharedApplication];
  363. }