platform-osx.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 SetDisplayAffinitySupported(void)
  103. {
  104. // Not implemented yet
  105. return false;
  106. }
  107. typedef void (*set_int_t)(int);
  108. void EnableOSXVSync(bool enable)
  109. {
  110. static bool initialized = false;
  111. static bool valid = false;
  112. static set_int_t set_debug_options = nullptr;
  113. static set_int_t deferred_updates = nullptr;
  114. if (!initialized) {
  115. void *quartzCore = dlopen("/System/Library/Frameworks/"
  116. "QuartzCore.framework/QuartzCore",
  117. RTLD_LAZY);
  118. if (quartzCore) {
  119. set_debug_options = (set_int_t) dlsym(quartzCore, "CGSSetDebugOptions");
  120. deferred_updates = (set_int_t) dlsym(quartzCore, "CGSDeferredUpdates");
  121. valid = set_debug_options && deferred_updates;
  122. }
  123. initialized = true;
  124. }
  125. if (valid) {
  126. set_debug_options(enable ? 0 : 0x08000000);
  127. deferred_updates(enable ? 1 : 0);
  128. }
  129. }
  130. void EnableOSXDockIcon(bool enable)
  131. {
  132. if (enable)
  133. [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
  134. else
  135. [NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited];
  136. }
  137. @interface DockView : NSView {
  138. @private
  139. QIcon _icon;
  140. }
  141. @end
  142. @implementation DockView
  143. - (id)initWithIcon:(QIcon)icon
  144. {
  145. self = [super init];
  146. _icon = icon;
  147. return self;
  148. }
  149. - (void)drawRect:(NSRect)dirtyRect
  150. {
  151. CGSize size = dirtyRect.size;
  152. /* Draw regular app icon */
  153. NSImage *appIcon = [[NSWorkspace sharedWorkspace] iconForFile:[[NSBundle mainBundle] bundlePath]];
  154. [appIcon drawInRect:CGRectMake(0, 0, size.width, size.height)];
  155. /* Draw small icon on top */
  156. float iconSize = 0.45;
  157. CGImageRef image = _icon.pixmap(size.width, size.height).toImage().toCGImage();
  158. CGContextRef context = [[NSGraphicsContext currentContext] CGContext];
  159. CGContextDrawImage(
  160. context, CGRectMake(size.width * (1 - iconSize), 0, size.width * iconSize, size.height * iconSize), image);
  161. CGImageRelease(image);
  162. }
  163. @end
  164. MacPermissionStatus CheckPermissionWithPrompt(MacPermissionType type, bool prompt_for_permission)
  165. {
  166. __block MacPermissionStatus permissionResponse = kPermissionNotDetermined;
  167. switch (type) {
  168. case kAudioDeviceAccess: {
  169. AVAuthorizationStatus audioStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
  170. if (audioStatus == AVAuthorizationStatusNotDetermined && prompt_for_permission) {
  171. os_event_t *block_finished;
  172. os_event_init(&block_finished, OS_EVENT_TYPE_MANUAL);
  173. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio
  174. completionHandler:^(BOOL granted __attribute((unused))) {
  175. os_event_signal(block_finished);
  176. }];
  177. os_event_wait(block_finished);
  178. os_event_destroy(block_finished);
  179. audioStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
  180. }
  181. permissionResponse = (MacPermissionStatus) audioStatus;
  182. blog(LOG_INFO, "[macOS] Permission for audio device access %s.",
  183. permissionResponse == kPermissionAuthorized ? "granted" : "denied");
  184. break;
  185. }
  186. case kVideoDeviceAccess: {
  187. AVAuthorizationStatus videoStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  188. if (videoStatus == AVAuthorizationStatusNotDetermined && prompt_for_permission) {
  189. os_event_t *block_finished;
  190. os_event_init(&block_finished, OS_EVENT_TYPE_MANUAL);
  191. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo
  192. completionHandler:^(BOOL granted __attribute((unused))) {
  193. os_event_signal(block_finished);
  194. }];
  195. os_event_wait(block_finished);
  196. os_event_destroy(block_finished);
  197. videoStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  198. }
  199. permissionResponse = (MacPermissionStatus) videoStatus;
  200. blog(LOG_INFO, "[macOS] Permission for video device access %s.",
  201. permissionResponse == kPermissionAuthorized ? "granted" : "denied");
  202. break;
  203. }
  204. case kScreenCapture: {
  205. permissionResponse = (CGPreflightScreenCaptureAccess() ? kPermissionAuthorized : kPermissionDenied);
  206. if (permissionResponse != kPermissionAuthorized && prompt_for_permission) {
  207. permissionResponse = (CGRequestScreenCaptureAccess() ? kPermissionAuthorized : kPermissionDenied);
  208. }
  209. blog(LOG_INFO, "[macOS] Permission for screen capture %s.",
  210. permissionResponse == kPermissionAuthorized ? "granted" : "denied");
  211. break;
  212. }
  213. case kAccessibility: {
  214. permissionResponse = (AXIsProcessTrusted() ? kPermissionAuthorized : kPermissionDenied);
  215. if (permissionResponse != kPermissionAuthorized && prompt_for_permission) {
  216. NSDictionary *options = @{(__bridge id) kAXTrustedCheckOptionPrompt: @YES};
  217. permissionResponse = (AXIsProcessTrustedWithOptions((CFDictionaryRef) options) ? kPermissionAuthorized
  218. : kPermissionDenied);
  219. }
  220. blog(LOG_INFO, "[macOS] Permission for accessibility %s.",
  221. permissionResponse == kPermissionAuthorized ? "granted" : "denied");
  222. break;
  223. }
  224. }
  225. return permissionResponse;
  226. }
  227. void OpenMacOSPrivacyPreferences(const char *tab)
  228. {
  229. NSURL *url = [NSURL
  230. URLWithString:[NSString
  231. stringWithFormat:@"x-apple.systempreferences:com.apple.preference.security?Privacy_%s", tab]];
  232. [[NSWorkspace sharedWorkspace] openURL:url];
  233. }
  234. void SetMacOSDarkMode(bool dark)
  235. {
  236. if (dark) {
  237. NSApp.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
  238. } else {
  239. NSApp.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
  240. }
  241. }
  242. void TaskbarOverlayInit() {}
  243. void TaskbarOverlaySetStatus(TaskbarOverlayStatus status)
  244. {
  245. QIcon icon;
  246. if (status == TaskbarOverlayStatusActive)
  247. icon = QIcon::fromTheme("obs-active", QIcon(":/res/images/active_mac.png"));
  248. else if (status == TaskbarOverlayStatusPaused)
  249. icon = QIcon::fromTheme("obs-paused", QIcon(":/res/images/paused_mac.png"));
  250. NSDockTile *tile = [NSApp dockTile];
  251. [tile setContentView:[[DockView alloc] initWithIcon:icon]];
  252. [tile display];
  253. }
  254. /*
  255. * This custom NSApplication subclass makes the app compatible with CEF. Qt
  256. * also has an NSApplication subclass, but it doesn't conflict thanks to Qt
  257. * using arcane magic to hook into the NSApplication superclass itself if the
  258. * program has its own NSApplication subclass.
  259. */
  260. @protocol CrAppProtocol
  261. - (BOOL)isHandlingSendEvent;
  262. @end
  263. @interface OBSApplication : NSApplication <CrAppProtocol>
  264. @property (nonatomic, getter=isHandlingSendEvent) BOOL handlingSendEvent;
  265. @end
  266. @implementation OBSApplication
  267. - (void)sendEvent:(NSEvent *)event
  268. {
  269. _handlingSendEvent = YES;
  270. [super sendEvent:event];
  271. _handlingSendEvent = NO;
  272. }
  273. @end
  274. void InstallNSThreadLocks()
  275. {
  276. [[NSThread new] start];
  277. if ([NSThread isMultiThreaded] != 1) {
  278. abort();
  279. }
  280. }
  281. void InstallNSApplicationSubclass()
  282. {
  283. [OBSApplication sharedApplication];
  284. }