os_macos.mm 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. /**************************************************************************/
  2. /* os_macos.mm */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "os_macos.h"
  31. #include "dir_access_macos.h"
  32. #include "display_server_macos.h"
  33. #include "godot_application.h"
  34. #include "godot_application_delegate.h"
  35. #include "macos_terminal_logger.h"
  36. #include "core/crypto/crypto_core.h"
  37. #include "core/version_generated.gen.h"
  38. #include "main/main.h"
  39. #include <dlfcn.h>
  40. #include <libproc.h>
  41. #include <mach-o/dyld.h>
  42. #include <os/log.h>
  43. #include <sys/sysctl.h>
  44. void OS_MacOS::pre_wait_observer_cb(CFRunLoopObserverRef p_observer, CFRunLoopActivity p_activiy, void *p_context) {
  45. // Prevent main loop from sleeping and redraw window during modal popup display.
  46. // Do not redraw when rendering is done from the separate thread, it will conflict with the OpenGL context updates.
  47. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  48. if (get_singleton()->get_main_loop() && ds && (get_singleton()->get_render_thread_mode() != RENDER_SEPARATE_THREAD) && !ds->get_is_resizing()) {
  49. Main::force_redraw();
  50. if (!Main::is_iterating()) { // Avoid cyclic loop.
  51. Main::iteration();
  52. }
  53. }
  54. CFRunLoopWakeUp(CFRunLoopGetCurrent()); // Prevent main loop from sleeping.
  55. }
  56. void OS_MacOS::initialize() {
  57. crash_handler.initialize();
  58. initialize_core();
  59. }
  60. String OS_MacOS::get_processor_name() const {
  61. char buffer[256];
  62. size_t buffer_len = 256;
  63. if (sysctlbyname("machdep.cpu.brand_string", &buffer, &buffer_len, NULL, 0) == 0) {
  64. return String::utf8(buffer, buffer_len);
  65. }
  66. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name. Returning an empty string."));
  67. }
  68. bool OS_MacOS::is_sandboxed() const {
  69. return has_environment("APP_SANDBOX_CONTAINER_ID");
  70. }
  71. Vector<String> OS_MacOS::get_granted_permissions() const {
  72. Vector<String> ret;
  73. if (is_sandboxed()) {
  74. NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"];
  75. for (id bookmark in bookmarks) {
  76. NSError *error = nil;
  77. BOOL isStale = NO;
  78. NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
  79. if (!error && !isStale) {
  80. String url_string;
  81. url_string.parse_utf8([[url path] UTF8String]);
  82. ret.push_back(url_string);
  83. }
  84. }
  85. }
  86. return ret;
  87. }
  88. void OS_MacOS::revoke_granted_permissions() {
  89. if (is_sandboxed()) {
  90. [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"sec_bookmarks"];
  91. }
  92. }
  93. void OS_MacOS::initialize_core() {
  94. OS_Unix::initialize_core();
  95. DirAccess::make_default<DirAccessMacOS>(DirAccess::ACCESS_RESOURCES);
  96. DirAccess::make_default<DirAccessMacOS>(DirAccess::ACCESS_USERDATA);
  97. DirAccess::make_default<DirAccessMacOS>(DirAccess::ACCESS_FILESYSTEM);
  98. }
  99. void OS_MacOS::finalize() {
  100. if (is_sandboxed()) {
  101. NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"];
  102. for (id bookmark in bookmarks) {
  103. NSError *error = nil;
  104. BOOL isStale = NO;
  105. NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
  106. if (!error && !isStale) {
  107. [url stopAccessingSecurityScopedResource];
  108. }
  109. }
  110. }
  111. #ifdef COREMIDI_ENABLED
  112. midi_driver.close();
  113. #endif
  114. delete_main_loop();
  115. if (joypad_macos) {
  116. memdelete(joypad_macos);
  117. }
  118. }
  119. void OS_MacOS::initialize_joypads() {
  120. joypad_macos = memnew(JoypadMacOS(Input::get_singleton()));
  121. }
  122. void OS_MacOS::set_main_loop(MainLoop *p_main_loop) {
  123. main_loop = p_main_loop;
  124. }
  125. void OS_MacOS::delete_main_loop() {
  126. if (!main_loop) {
  127. return;
  128. }
  129. memdelete(main_loop);
  130. main_loop = nullptr;
  131. }
  132. void OS_MacOS::set_cmdline_platform_args(const List<String> &p_args) {
  133. launch_service_args = p_args;
  134. }
  135. List<String> OS_MacOS::get_cmdline_platform_args() const {
  136. return launch_service_args;
  137. }
  138. String OS_MacOS::get_name() const {
  139. return "macOS";
  140. }
  141. String OS_MacOS::get_distribution_name() const {
  142. return get_name();
  143. }
  144. String OS_MacOS::get_version() const {
  145. NSOperatingSystemVersion ver = [NSProcessInfo processInfo].operatingSystemVersion;
  146. return vformat("%d.%d.%d", (int64_t)ver.majorVersion, (int64_t)ver.minorVersion, (int64_t)ver.patchVersion);
  147. }
  148. void OS_MacOS::alert(const String &p_alert, const String &p_title) {
  149. NSAlert *window = [[NSAlert alloc] init];
  150. NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
  151. NSString *ns_alert = [NSString stringWithUTF8String:p_alert.utf8().get_data()];
  152. NSTextField *text_field = [NSTextField labelWithString:ns_alert];
  153. [text_field setAlignment:NSTextAlignmentCenter];
  154. [window addButtonWithTitle:@"OK"];
  155. [window setMessageText:ns_title];
  156. [window setAccessoryView:text_field];
  157. [window setAlertStyle:NSAlertStyleWarning];
  158. id key_window = [[NSApplication sharedApplication] keyWindow];
  159. [window runModal];
  160. if (key_window) {
  161. [key_window makeKeyAndOrderFront:nil];
  162. }
  163. }
  164. _FORCE_INLINE_ String OS_MacOS::get_framework_executable(const String &p_path) {
  165. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  166. // Read framework bundle to get executable name.
  167. NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
  168. NSBundle *bundle = [NSBundle bundleWithURL:url];
  169. if (bundle) {
  170. String exe_path = String::utf8([[bundle executablePath] UTF8String]);
  171. if (da->file_exists(exe_path)) {
  172. return exe_path;
  173. }
  174. }
  175. // Try default executable name (invalid framework).
  176. if (da->dir_exists(p_path) && da->file_exists(p_path.path_join(p_path.get_file().get_basename()))) {
  177. return p_path.path_join(p_path.get_file().get_basename());
  178. }
  179. // Not a framework, try loading as .dylib.
  180. return p_path;
  181. }
  182. Error OS_MacOS::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path, String *r_resolved_path) {
  183. String path = get_framework_executable(p_path);
  184. if (!FileAccess::exists(path)) {
  185. // Load .dylib or framework from within the executable path.
  186. path = get_framework_executable(get_executable_path().get_base_dir().path_join(p_path.get_file()));
  187. }
  188. if (!FileAccess::exists(path)) {
  189. // Load .dylib or framework from a standard macOS location.
  190. path = get_framework_executable(get_executable_path().get_base_dir().path_join("../Frameworks").path_join(p_path.get_file()));
  191. }
  192. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  193. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, vformat("Can't open dynamic library: %s. Error: %s.", p_path, dlerror()));
  194. if (r_resolved_path != nullptr) {
  195. *r_resolved_path = path;
  196. }
  197. return OK;
  198. }
  199. MainLoop *OS_MacOS::get_main_loop() const {
  200. return main_loop;
  201. }
  202. String OS_MacOS::get_config_path() const {
  203. if (has_environment("HOME")) {
  204. return get_environment("HOME").path_join("Library/Application Support");
  205. }
  206. return ".";
  207. }
  208. String OS_MacOS::get_data_path() const {
  209. return get_config_path();
  210. }
  211. String OS_MacOS::get_cache_path() const {
  212. if (has_environment("HOME")) {
  213. return get_environment("HOME").path_join("Library/Caches");
  214. }
  215. return get_config_path();
  216. }
  217. String OS_MacOS::get_bundle_resource_dir() const {
  218. String ret;
  219. NSBundle *main = [NSBundle mainBundle];
  220. if (main) {
  221. NSString *resource_path = [main resourcePath];
  222. ret.parse_utf8([resource_path UTF8String]);
  223. }
  224. return ret;
  225. }
  226. String OS_MacOS::get_bundle_icon_path() const {
  227. String ret;
  228. NSBundle *main = [NSBundle mainBundle];
  229. if (main) {
  230. NSString *icon_path = [[main infoDictionary] objectForKey:@"CFBundleIconFile"];
  231. if (icon_path) {
  232. ret.parse_utf8([icon_path UTF8String]);
  233. }
  234. }
  235. return ret;
  236. }
  237. // Get properly capitalized engine name for system paths
  238. String OS_MacOS::get_godot_dir_name() const {
  239. return String(VERSION_SHORT_NAME).capitalize();
  240. }
  241. String OS_MacOS::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  242. NSSearchPathDirectory id;
  243. bool found = true;
  244. switch (p_dir) {
  245. case SYSTEM_DIR_DESKTOP: {
  246. id = NSDesktopDirectory;
  247. } break;
  248. case SYSTEM_DIR_DOCUMENTS: {
  249. id = NSDocumentDirectory;
  250. } break;
  251. case SYSTEM_DIR_DOWNLOADS: {
  252. id = NSDownloadsDirectory;
  253. } break;
  254. case SYSTEM_DIR_MOVIES: {
  255. id = NSMoviesDirectory;
  256. } break;
  257. case SYSTEM_DIR_MUSIC: {
  258. id = NSMusicDirectory;
  259. } break;
  260. case SYSTEM_DIR_PICTURES: {
  261. id = NSPicturesDirectory;
  262. } break;
  263. default: {
  264. found = false;
  265. }
  266. }
  267. String ret;
  268. if (found) {
  269. NSArray *paths = NSSearchPathForDirectoriesInDomains(id, NSUserDomainMask, YES);
  270. if (paths && [paths count] >= 1) {
  271. ret.parse_utf8([[paths firstObject] UTF8String]);
  272. }
  273. }
  274. return ret;
  275. }
  276. Error OS_MacOS::shell_show_in_file_manager(String p_path, bool p_open_folder) {
  277. bool open_folder = false;
  278. if (DirAccess::dir_exists_absolute(p_path) && p_open_folder) {
  279. open_folder = true;
  280. }
  281. if (!p_path.begins_with("file://")) {
  282. p_path = String("file://") + p_path;
  283. }
  284. NSString *string = [NSString stringWithUTF8String:p_path.utf8().get_data()];
  285. NSURL *uri = [[NSURL alloc] initWithString:[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
  286. if (open_folder) {
  287. [[NSWorkspace sharedWorkspace] openURL:uri];
  288. } else {
  289. [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[ uri ]];
  290. }
  291. return OK;
  292. }
  293. Error OS_MacOS::shell_open(String p_uri) {
  294. NSString *string = [NSString stringWithUTF8String:p_uri.utf8().get_data()];
  295. NSURL *uri = [[NSURL alloc] initWithString:string];
  296. // Escape special characters in filenames
  297. if (!uri || !uri.scheme || [uri.scheme isEqual:@"file"]) {
  298. uri = [[NSURL alloc] initWithString:[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
  299. }
  300. [[NSWorkspace sharedWorkspace] openURL:uri];
  301. return OK;
  302. }
  303. String OS_MacOS::get_locale() const {
  304. NSString *locale_code = [[NSLocale preferredLanguages] objectAtIndex:0];
  305. return String([locale_code UTF8String]).replace("-", "_");
  306. }
  307. Vector<String> OS_MacOS::get_system_fonts() const {
  308. HashSet<String> font_names;
  309. CFArrayRef fonts = CTFontManagerCopyAvailableFontFamilyNames();
  310. if (fonts) {
  311. for (CFIndex i = 0; i < CFArrayGetCount(fonts); i++) {
  312. CFStringRef cf_name = (CFStringRef)CFArrayGetValueAtIndex(fonts, i);
  313. if (cf_name && (CFStringGetLength(cf_name) > 0) && (CFStringCompare(cf_name, CFSTR("LastResort"), kCFCompareCaseInsensitive) != kCFCompareEqualTo) && (CFStringGetCharacterAtIndex(cf_name, 0) != '.')) {
  314. NSString *ns_name = (__bridge NSString *)cf_name;
  315. font_names.insert(String::utf8([ns_name UTF8String]));
  316. }
  317. }
  318. CFRelease(fonts);
  319. }
  320. Vector<String> ret;
  321. for (const String &E : font_names) {
  322. ret.push_back(E);
  323. }
  324. return ret;
  325. }
  326. String OS_MacOS::_get_default_fontname(const String &p_font_name) const {
  327. String font_name = p_font_name;
  328. if (font_name.to_lower() == "sans-serif") {
  329. font_name = "Helvetica";
  330. } else if (font_name.to_lower() == "serif") {
  331. font_name = "Times";
  332. } else if (font_name.to_lower() == "monospace") {
  333. font_name = "Courier";
  334. } else if (font_name.to_lower() == "fantasy") {
  335. font_name = "Papyrus";
  336. } else if (font_name.to_lower() == "cursive") {
  337. font_name = "Apple Chancery";
  338. };
  339. return font_name;
  340. }
  341. CGFloat OS_MacOS::_weight_to_ct(int p_weight) const {
  342. if (p_weight < 150) {
  343. return -0.80;
  344. } else if (p_weight < 250) {
  345. return -0.60;
  346. } else if (p_weight < 350) {
  347. return -0.40;
  348. } else if (p_weight < 450) {
  349. return 0.0;
  350. } else if (p_weight < 550) {
  351. return 0.23;
  352. } else if (p_weight < 650) {
  353. return 0.30;
  354. } else if (p_weight < 750) {
  355. return 0.40;
  356. } else if (p_weight < 850) {
  357. return 0.56;
  358. } else if (p_weight < 925) {
  359. return 0.62;
  360. } else {
  361. return 1.00;
  362. }
  363. }
  364. CGFloat OS_MacOS::_stretch_to_ct(int p_stretch) const {
  365. if (p_stretch < 56) {
  366. return -0.5;
  367. } else if (p_stretch < 69) {
  368. return -0.37;
  369. } else if (p_stretch < 81) {
  370. return -0.25;
  371. } else if (p_stretch < 93) {
  372. return -0.13;
  373. } else if (p_stretch < 106) {
  374. return 0.0;
  375. } else if (p_stretch < 137) {
  376. return 0.13;
  377. } else if (p_stretch < 144) {
  378. return 0.25;
  379. } else if (p_stretch < 162) {
  380. return 0.37;
  381. } else {
  382. return 0.5;
  383. }
  384. }
  385. Vector<String> OS_MacOS::get_system_font_path_for_text(const String &p_font_name, const String &p_text, const String &p_locale, const String &p_script, int p_weight, int p_stretch, bool p_italic) const {
  386. Vector<String> ret;
  387. String font_name = _get_default_fontname(p_font_name);
  388. CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, font_name.utf8().get_data(), kCFStringEncodingUTF8);
  389. CTFontSymbolicTraits traits = 0;
  390. if (p_weight >= 700) {
  391. traits |= kCTFontBoldTrait;
  392. }
  393. if (p_italic) {
  394. traits |= kCTFontItalicTrait;
  395. }
  396. if (p_stretch < 100) {
  397. traits |= kCTFontCondensedTrait;
  398. } else if (p_stretch > 100) {
  399. traits |= kCTFontExpandedTrait;
  400. }
  401. CFNumberRef sym_traits = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &traits);
  402. CFMutableDictionaryRef traits_dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
  403. CFDictionaryAddValue(traits_dict, kCTFontSymbolicTrait, sym_traits);
  404. CGFloat weight = _weight_to_ct(p_weight);
  405. CFNumberRef font_weight = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &weight);
  406. CFDictionaryAddValue(traits_dict, kCTFontWeightTrait, font_weight);
  407. CGFloat stretch = _stretch_to_ct(p_stretch);
  408. CFNumberRef font_stretch = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &stretch);
  409. CFDictionaryAddValue(traits_dict, kCTFontWidthTrait, font_stretch);
  410. CFMutableDictionaryRef attributes = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
  411. CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, name);
  412. CFDictionaryAddValue(attributes, kCTFontTraitsAttribute, traits_dict);
  413. CTFontDescriptorRef font = CTFontDescriptorCreateWithAttributes(attributes);
  414. if (font) {
  415. CTFontRef family = CTFontCreateWithFontDescriptor(font, 0, nullptr);
  416. CFStringRef string = CFStringCreateWithCString(kCFAllocatorDefault, p_text.utf8().get_data(), kCFStringEncodingUTF8);
  417. CFRange range = CFRangeMake(0, CFStringGetLength(string));
  418. CTFontRef fallback_family = CTFontCreateForString(family, string, range);
  419. if (fallback_family) {
  420. CTFontDescriptorRef fallback_font = CTFontCopyFontDescriptor(fallback_family);
  421. if (fallback_font) {
  422. CFURLRef url = (CFURLRef)CTFontDescriptorCopyAttribute(fallback_font, kCTFontURLAttribute);
  423. if (url) {
  424. NSString *font_path = [NSString stringWithString:[(__bridge NSURL *)url path]];
  425. ret.push_back(String::utf8([font_path UTF8String]));
  426. CFRelease(url);
  427. }
  428. CFRelease(fallback_font);
  429. }
  430. CFRelease(fallback_family);
  431. }
  432. CFRelease(string);
  433. CFRelease(font);
  434. }
  435. CFRelease(attributes);
  436. CFRelease(traits_dict);
  437. CFRelease(sym_traits);
  438. CFRelease(font_stretch);
  439. CFRelease(font_weight);
  440. CFRelease(name);
  441. return ret;
  442. }
  443. String OS_MacOS::get_system_font_path(const String &p_font_name, int p_weight, int p_stretch, bool p_italic) const {
  444. String ret;
  445. String font_name = _get_default_fontname(p_font_name);
  446. CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, font_name.utf8().get_data(), kCFStringEncodingUTF8);
  447. CTFontSymbolicTraits traits = 0;
  448. if (p_weight > 700) {
  449. traits |= kCTFontBoldTrait;
  450. }
  451. if (p_italic) {
  452. traits |= kCTFontItalicTrait;
  453. }
  454. if (p_stretch < 100) {
  455. traits |= kCTFontCondensedTrait;
  456. } else if (p_stretch > 100) {
  457. traits |= kCTFontExpandedTrait;
  458. }
  459. CFNumberRef sym_traits = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &traits);
  460. CFMutableDictionaryRef traits_dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
  461. CFDictionaryAddValue(traits_dict, kCTFontSymbolicTrait, sym_traits);
  462. CGFloat weight = _weight_to_ct(p_weight);
  463. CFNumberRef font_weight = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &weight);
  464. CFDictionaryAddValue(traits_dict, kCTFontWeightTrait, font_weight);
  465. CGFloat stretch = _stretch_to_ct(p_stretch);
  466. CFNumberRef font_stretch = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &stretch);
  467. CFDictionaryAddValue(traits_dict, kCTFontWidthTrait, font_stretch);
  468. CFMutableDictionaryRef attributes = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
  469. CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, name);
  470. CFDictionaryAddValue(attributes, kCTFontTraitsAttribute, traits_dict);
  471. CTFontDescriptorRef font = CTFontDescriptorCreateWithAttributes(attributes);
  472. if (font) {
  473. CFURLRef url = (CFURLRef)CTFontDescriptorCopyAttribute(font, kCTFontURLAttribute);
  474. if (url) {
  475. NSString *font_path = [NSString stringWithString:[(__bridge NSURL *)url path]];
  476. ret = String::utf8([font_path UTF8String]);
  477. CFRelease(url);
  478. }
  479. CFRelease(font);
  480. }
  481. CFRelease(attributes);
  482. CFRelease(traits_dict);
  483. CFRelease(sym_traits);
  484. CFRelease(font_stretch);
  485. CFRelease(font_weight);
  486. CFRelease(name);
  487. return ret;
  488. }
  489. String OS_MacOS::get_executable_path() const {
  490. char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
  491. int pid = getpid();
  492. pid_t ret = proc_pidpath(pid, pathbuf, sizeof(pathbuf));
  493. if (ret <= 0) {
  494. return OS::get_executable_path();
  495. } else {
  496. String path;
  497. path.parse_utf8(pathbuf);
  498. return path;
  499. }
  500. }
  501. Error OS_MacOS::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
  502. // Use NSWorkspace if path is an .app bundle.
  503. NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
  504. NSBundle *bundle = [NSBundle bundleWithURL:url];
  505. if (bundle) {
  506. NSMutableArray *arguments = [[NSMutableArray alloc] init];
  507. for (const String &arg : p_arguments) {
  508. [arguments addObject:[NSString stringWithUTF8String:arg.utf8().get_data()]];
  509. }
  510. if (@available(macOS 10.15, *)) {
  511. NSWorkspaceOpenConfiguration *configuration = [[NSWorkspaceOpenConfiguration alloc] init];
  512. [configuration setArguments:arguments];
  513. [configuration setCreatesNewApplicationInstance:YES];
  514. __block dispatch_semaphore_t lock = dispatch_semaphore_create(0);
  515. __block Error err = ERR_TIMEOUT;
  516. __block pid_t pid = 0;
  517. [[NSWorkspace sharedWorkspace] openApplicationAtURL:url
  518. configuration:configuration
  519. completionHandler:^(NSRunningApplication *app, NSError *error) {
  520. if (error) {
  521. err = ERR_CANT_FORK;
  522. NSLog(@"Failed to execute: %@", error.localizedDescription);
  523. } else {
  524. pid = [app processIdentifier];
  525. err = OK;
  526. }
  527. dispatch_semaphore_signal(lock);
  528. }];
  529. dispatch_semaphore_wait(lock, dispatch_time(DISPATCH_TIME_NOW, 20000000000)); // 20 sec timeout, wait for app to launch.
  530. if (err == OK) {
  531. if (r_child_id) {
  532. *r_child_id = (ProcessID)pid;
  533. }
  534. }
  535. return err;
  536. } else {
  537. Error err = ERR_TIMEOUT;
  538. NSError *error = nullptr;
  539. NSRunningApplication *app = [[NSWorkspace sharedWorkspace] launchApplicationAtURL:url options:NSWorkspaceLaunchNewInstance configuration:[NSDictionary dictionaryWithObject:arguments forKey:NSWorkspaceLaunchConfigurationArguments] error:&error];
  540. if (error) {
  541. err = ERR_CANT_FORK;
  542. NSLog(@"Failed to execute: %@", error.localizedDescription);
  543. } else {
  544. if (r_child_id) {
  545. *r_child_id = (ProcessID)[app processIdentifier];
  546. }
  547. err = OK;
  548. }
  549. return err;
  550. }
  551. } else {
  552. return OS_Unix::create_process(p_path, p_arguments, r_child_id, p_open_console);
  553. }
  554. }
  555. Error OS_MacOS::create_instance(const List<String> &p_arguments, ProcessID *r_child_id) {
  556. // If executable is bundled, always execute editor instances as an app bundle to ensure app window is registered and activated correctly.
  557. NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  558. if (nsappname != nil) {
  559. String path;
  560. path.parse_utf8([[[NSBundle mainBundle] bundlePath] UTF8String]);
  561. return create_process(path, p_arguments, r_child_id, false);
  562. } else {
  563. return create_process(get_executable_path(), p_arguments, r_child_id, false);
  564. }
  565. }
  566. String OS_MacOS::get_unique_id() const {
  567. static String serial_number;
  568. if (serial_number.is_empty()) {
  569. io_service_t platform_expert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"));
  570. CFStringRef serial_number_cf_string = nullptr;
  571. if (platform_expert) {
  572. serial_number_cf_string = (CFStringRef)IORegistryEntryCreateCFProperty(platform_expert, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0);
  573. IOObjectRelease(platform_expert);
  574. }
  575. NSString *serial_number_ns_string = nil;
  576. if (serial_number_cf_string) {
  577. serial_number_ns_string = [NSString stringWithString:(__bridge NSString *)serial_number_cf_string];
  578. CFRelease(serial_number_cf_string);
  579. }
  580. if (serial_number_ns_string) {
  581. serial_number.parse_utf8([serial_number_ns_string UTF8String]);
  582. }
  583. }
  584. return serial_number;
  585. }
  586. bool OS_MacOS::_check_internal_feature_support(const String &p_feature) {
  587. if (p_feature == "system_fonts") {
  588. return true;
  589. }
  590. if (p_feature == "pc") {
  591. return true;
  592. }
  593. return false;
  594. }
  595. void OS_MacOS::disable_crash_handler() {
  596. crash_handler.disable();
  597. }
  598. bool OS_MacOS::is_disable_crash_handler() const {
  599. return crash_handler.is_disabled();
  600. }
  601. Error OS_MacOS::move_to_trash(const String &p_path) {
  602. NSFileManager *fm = [NSFileManager defaultManager];
  603. NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
  604. NSError *err;
  605. if (![fm trashItemAtURL:url resultingItemURL:nil error:&err]) {
  606. ERR_PRINT("trashItemAtURL error: " + String::utf8(err.localizedDescription.UTF8String));
  607. return FAILED;
  608. }
  609. return OK;
  610. }
  611. String OS_MacOS::get_system_ca_certificates() {
  612. CFArrayRef result;
  613. SecCertificateRef item;
  614. CFDataRef der;
  615. OSStatus ret = SecTrustCopyAnchorCertificates(&result);
  616. ERR_FAIL_COND_V(ret != noErr, "");
  617. CFIndex l = CFArrayGetCount(result);
  618. String certs;
  619. PackedByteArray pba;
  620. for (CFIndex i = 0; i < l; i++) {
  621. item = (SecCertificateRef)CFArrayGetValueAtIndex(result, i);
  622. der = SecCertificateCopyData(item);
  623. int derlen = CFDataGetLength(der);
  624. if (pba.size() < derlen * 3) {
  625. pba.resize(derlen * 3);
  626. }
  627. size_t b64len = 0;
  628. Error err = CryptoCore::b64_encode(pba.ptrw(), pba.size(), &b64len, (unsigned char *)CFDataGetBytePtr(der), derlen);
  629. CFRelease(der);
  630. ERR_CONTINUE(err != OK);
  631. certs += "-----BEGIN CERTIFICATE-----\n" + String((char *)pba.ptr(), b64len) + "\n-----END CERTIFICATE-----\n";
  632. }
  633. CFRelease(result);
  634. return certs;
  635. }
  636. OS::PreferredTextureFormat OS_MacOS::get_preferred_texture_format() const {
  637. // macOS supports both formats on ARM. Prefer S3TC/BPTC
  638. // for better compatibility with x86 platforms.
  639. return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC;
  640. }
  641. void OS_MacOS::run() {
  642. if (!main_loop) {
  643. return;
  644. }
  645. main_loop->initialize();
  646. bool quit = false;
  647. while (!quit) {
  648. @try {
  649. if (DisplayServer::get_singleton()) {
  650. DisplayServer::get_singleton()->process_events(); // Get rid of pending events.
  651. }
  652. joypad_macos->process_joypads();
  653. if (Main::iteration()) {
  654. quit = true;
  655. }
  656. } @catch (NSException *exception) {
  657. ERR_PRINT("NSException: " + String::utf8([exception reason].UTF8String));
  658. }
  659. }
  660. main_loop->finalize();
  661. }
  662. OS_MacOS::OS_MacOS() {
  663. if (is_sandboxed()) {
  664. // Load security-scoped bookmarks, request access, remove stale or invalid bookmarks.
  665. NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"];
  666. NSMutableArray *new_bookmarks = [[NSMutableArray alloc] init];
  667. for (id bookmark in bookmarks) {
  668. NSError *error = nil;
  669. BOOL isStale = NO;
  670. NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
  671. if (!error && !isStale) {
  672. if ([url startAccessingSecurityScopedResource]) {
  673. [new_bookmarks addObject:bookmark];
  674. }
  675. }
  676. }
  677. [[NSUserDefaults standardUserDefaults] setObject:new_bookmarks forKey:@"sec_bookmarks"];
  678. }
  679. main_loop = nullptr;
  680. Vector<Logger *> loggers;
  681. loggers.push_back(memnew(MacOSTerminalLogger));
  682. _set_logger(memnew(CompositeLogger(loggers)));
  683. #ifdef COREAUDIO_ENABLED
  684. AudioDriverManager::add_driver(&audio_driver);
  685. #endif
  686. DisplayServerMacOS::register_macos_driver();
  687. // Implicitly create shared NSApplication instance.
  688. [GodotApplication sharedApplication];
  689. // In case we are unbundled, make us a proper UI application.
  690. [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
  691. // Menu bar setup must go between sharedApplication above and
  692. // finishLaunching below, in order to properly emulate the behavior
  693. // of NSApplicationMain.
  694. NSMenu *main_menu = [[NSMenu alloc] initWithTitle:@""];
  695. [NSApp setMainMenu:main_menu];
  696. [NSApp finishLaunching];
  697. id delegate = [[GodotApplicationDelegate alloc] init];
  698. ERR_FAIL_COND(!delegate);
  699. [NSApp setDelegate:delegate];
  700. pre_wait_observer = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, true, 0, &pre_wait_observer_cb, nullptr);
  701. CFRunLoopAddObserver(CFRunLoopGetCurrent(), pre_wait_observer, kCFRunLoopCommonModes);
  702. // Process application:openFile: event.
  703. while (true) {
  704. NSEvent *event = [NSApp
  705. nextEventMatchingMask:NSEventMaskAny
  706. untilDate:[NSDate distantPast]
  707. inMode:NSDefaultRunLoopMode
  708. dequeue:YES];
  709. if (event == nil) {
  710. break;
  711. }
  712. [NSApp sendEvent:event];
  713. }
  714. [NSApp activateIgnoringOtherApps:YES];
  715. }
  716. OS_MacOS::~OS_MacOS() {
  717. CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), pre_wait_observer, kCFRunLoopCommonModes);
  718. CFRelease(pre_wait_observer);
  719. }