platform-osx.mm 12 KB

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