platform-osx.mm 11 KB

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