platform-osx.mm 10 KB

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