platform-osx.mm 11 KB

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