platform-osx.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. if (@available(macOS 10.14, *)) {
  205. AVAuthorizationStatus audioStatus = [AVCaptureDevice
  206. authorizationStatusForMediaType:AVMediaTypeAudio];
  207. if (audioStatus == AVAuthorizationStatusNotDetermined &&
  208. prompt_for_permission) {
  209. os_event_t *block_finished;
  210. os_event_init(&block_finished,
  211. OS_EVENT_TYPE_MANUAL);
  212. [AVCaptureDevice
  213. requestAccessForMediaType:AVMediaTypeAudio
  214. completionHandler:^(
  215. BOOL granted
  216. __attribute((unused))) {
  217. os_event_signal(
  218. block_finished);
  219. }];
  220. os_event_wait(block_finished);
  221. os_event_destroy(block_finished);
  222. audioStatus = [AVCaptureDevice
  223. authorizationStatusForMediaType:
  224. AVMediaTypeAudio];
  225. }
  226. permissionResponse = (MacPermissionStatus)audioStatus;
  227. } else {
  228. permissionResponse = kPermissionAuthorized;
  229. }
  230. blog(LOG_INFO, "[macOS] Permission for audio device access %s.",
  231. permissionResponse == kPermissionAuthorized ? "granted"
  232. : "denied");
  233. break;
  234. }
  235. case kVideoDeviceAccess: {
  236. if (@available(macOS 10.14, *)) {
  237. AVAuthorizationStatus videoStatus = [AVCaptureDevice
  238. authorizationStatusForMediaType:AVMediaTypeVideo];
  239. if (videoStatus == AVAuthorizationStatusNotDetermined &&
  240. prompt_for_permission) {
  241. os_event_t *block_finished;
  242. os_event_init(&block_finished,
  243. OS_EVENT_TYPE_MANUAL);
  244. [AVCaptureDevice
  245. requestAccessForMediaType:AVMediaTypeVideo
  246. completionHandler:^(
  247. BOOL granted
  248. __attribute((unused))) {
  249. os_event_signal(
  250. block_finished);
  251. }];
  252. os_event_wait(block_finished);
  253. os_event_destroy(block_finished);
  254. videoStatus = [AVCaptureDevice
  255. authorizationStatusForMediaType:
  256. AVMediaTypeVideo];
  257. }
  258. permissionResponse = (MacPermissionStatus)videoStatus;
  259. } else {
  260. permissionResponse = kPermissionAuthorized;
  261. }
  262. blog(LOG_INFO, "[macOS] Permission for video device access %s.",
  263. permissionResponse == kPermissionAuthorized ? "granted"
  264. : "denied");
  265. break;
  266. }
  267. case kScreenCapture: {
  268. if (@available(macOS 11.0, *)) {
  269. permissionResponse = (CGPreflightScreenCaptureAccess()
  270. ? kPermissionAuthorized
  271. : kPermissionDenied);
  272. if (permissionResponse != kPermissionAuthorized &&
  273. prompt_for_permission) {
  274. permissionResponse =
  275. (CGRequestScreenCaptureAccess()
  276. ? kPermissionAuthorized
  277. : kPermissionDenied);
  278. }
  279. } else {
  280. permissionResponse = kPermissionAuthorized;
  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 TaskbarOverlayInit() {}
  310. void TaskbarOverlaySetStatus(TaskbarOverlayStatus status)
  311. {
  312. QIcon icon;
  313. if (status == TaskbarOverlayStatusActive)
  314. icon = QIcon::fromTheme("obs-active",
  315. QIcon(":/res/images/active_mac.png"));
  316. else if (status == TaskbarOverlayStatusPaused)
  317. icon = QIcon::fromTheme("obs-paused",
  318. QIcon(":/res/images/paused_mac.png"));
  319. NSDockTile *tile = [NSApp dockTile];
  320. [tile setContentView:[[DockView alloc] initWithIcon:icon]];
  321. [tile display];
  322. }
  323. /*
  324. * This custom NSApplication subclass makes the app compatible with CEF. Qt
  325. * also has an NSApplication subclass, but it doesn't conflict thanks to Qt
  326. * using arcane magic to hook into the NSApplication superclass itself if the
  327. * program has its own NSApplication subclass.
  328. */
  329. @protocol CrAppProtocol
  330. - (BOOL)isHandlingSendEvent;
  331. @end
  332. @interface OBSApplication : NSApplication <CrAppProtocol>
  333. @property (nonatomic, getter=isHandlingSendEvent) BOOL handlingSendEvent;
  334. @end
  335. @implementation OBSApplication
  336. - (void)sendEvent:(NSEvent *)event
  337. {
  338. _handlingSendEvent = YES;
  339. [super sendEvent:event];
  340. _handlingSendEvent = NO;
  341. }
  342. @end
  343. void InstallNSThreadLocks()
  344. {
  345. [[NSThread new] start];
  346. if ([NSThread isMultiThreaded] != 1) {
  347. abort();
  348. }
  349. }
  350. void InstallNSApplicationSubclass()
  351. {
  352. [OBSApplication sharedApplication];
  353. }