os_macos.mm 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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, nullptr, 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());
  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, GDExtensionData *p_data) {
  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. ERR_FAIL_COND_V(!FileAccess::exists(path), ERR_FILE_NOT_FOUND);
  193. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  194. ERR_FAIL_NULL_V_MSG(p_library_handle, ERR_CANT_OPEN, vformat("Can't open dynamic library: %s. Error: %s.", p_path, dlerror()));
  195. if (p_data != nullptr && p_data->r_resolved_path != nullptr) {
  196. *p_data->r_resolved_path = path;
  197. }
  198. return OK;
  199. }
  200. MainLoop *OS_MacOS::get_main_loop() const {
  201. return main_loop;
  202. }
  203. String OS_MacOS::get_config_path() const {
  204. if (has_environment("HOME")) {
  205. return get_environment("HOME").path_join("Library/Application Support");
  206. }
  207. return ".";
  208. }
  209. String OS_MacOS::get_data_path() const {
  210. return get_config_path();
  211. }
  212. String OS_MacOS::get_cache_path() const {
  213. if (has_environment("HOME")) {
  214. return get_environment("HOME").path_join("Library/Caches");
  215. }
  216. return get_config_path();
  217. }
  218. String OS_MacOS::get_bundle_resource_dir() const {
  219. String ret;
  220. NSBundle *main = [NSBundle mainBundle];
  221. if (main) {
  222. NSString *resource_path = [main resourcePath];
  223. ret.parse_utf8([resource_path UTF8String]);
  224. }
  225. return ret;
  226. }
  227. String OS_MacOS::get_bundle_icon_path() const {
  228. String ret;
  229. NSBundle *main = [NSBundle mainBundle];
  230. if (main) {
  231. NSString *icon_path = [[main infoDictionary] objectForKey:@"CFBundleIconFile"];
  232. if (icon_path) {
  233. ret.parse_utf8([icon_path UTF8String]);
  234. }
  235. }
  236. return ret;
  237. }
  238. // Get properly capitalized engine name for system paths
  239. String OS_MacOS::get_godot_dir_name() const {
  240. return String(VERSION_SHORT_NAME).capitalize();
  241. }
  242. String OS_MacOS::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  243. NSSearchPathDirectory id;
  244. bool found = true;
  245. switch (p_dir) {
  246. case SYSTEM_DIR_DESKTOP: {
  247. id = NSDesktopDirectory;
  248. } break;
  249. case SYSTEM_DIR_DOCUMENTS: {
  250. id = NSDocumentDirectory;
  251. } break;
  252. case SYSTEM_DIR_DOWNLOADS: {
  253. id = NSDownloadsDirectory;
  254. } break;
  255. case SYSTEM_DIR_MOVIES: {
  256. id = NSMoviesDirectory;
  257. } break;
  258. case SYSTEM_DIR_MUSIC: {
  259. id = NSMusicDirectory;
  260. } break;
  261. case SYSTEM_DIR_PICTURES: {
  262. id = NSPicturesDirectory;
  263. } break;
  264. default: {
  265. found = false;
  266. }
  267. }
  268. String ret;
  269. if (found) {
  270. NSArray *paths = NSSearchPathForDirectoriesInDomains(id, NSUserDomainMask, YES);
  271. if (paths && [paths count] >= 1) {
  272. ret.parse_utf8([[paths firstObject] UTF8String]);
  273. }
  274. }
  275. return ret;
  276. }
  277. Error OS_MacOS::shell_show_in_file_manager(String p_path, bool p_open_folder) {
  278. bool open_folder = false;
  279. if (DirAccess::dir_exists_absolute(p_path) && p_open_folder) {
  280. open_folder = true;
  281. }
  282. if (!p_path.begins_with("file://")) {
  283. p_path = String("file://") + p_path;
  284. }
  285. NSString *string = [NSString stringWithUTF8String:p_path.utf8().get_data()];
  286. NSURL *uri = [[NSURL alloc] initWithString:[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
  287. if (open_folder) {
  288. [[NSWorkspace sharedWorkspace] openURL:uri];
  289. } else {
  290. [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[ uri ]];
  291. }
  292. return OK;
  293. }
  294. Error OS_MacOS::shell_open(const String &p_uri) {
  295. NSString *string = [NSString stringWithUTF8String:p_uri.utf8().get_data()];
  296. NSURL *uri = [[NSURL alloc] initWithString:string];
  297. if (!uri || !uri.scheme || [uri.scheme isEqual:@"file"]) {
  298. // No scheme set, assume "file://" and escape special characters.
  299. if (!p_uri.begins_with("file://")) {
  300. string = [NSString stringWithUTF8String:("file://" + p_uri).utf8().get_data()];
  301. }
  302. uri = [[NSURL alloc] initWithString:[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
  303. }
  304. [[NSWorkspace sharedWorkspace] openURL:uri];
  305. return OK;
  306. }
  307. String OS_MacOS::get_locale() const {
  308. NSString *locale_code = [[NSLocale preferredLanguages] objectAtIndex:0];
  309. return String([locale_code UTF8String]).replace("-", "_");
  310. }
  311. Vector<String> OS_MacOS::get_system_fonts() const {
  312. HashSet<String> font_names;
  313. CFArrayRef fonts = CTFontManagerCopyAvailableFontFamilyNames();
  314. if (fonts) {
  315. for (CFIndex i = 0; i < CFArrayGetCount(fonts); i++) {
  316. CFStringRef cf_name = (CFStringRef)CFArrayGetValueAtIndex(fonts, i);
  317. if (cf_name && (CFStringGetLength(cf_name) > 0) && (CFStringCompare(cf_name, CFSTR("LastResort"), kCFCompareCaseInsensitive) != kCFCompareEqualTo) && (CFStringGetCharacterAtIndex(cf_name, 0) != '.')) {
  318. NSString *ns_name = (__bridge NSString *)cf_name;
  319. font_names.insert(String::utf8([ns_name UTF8String]));
  320. }
  321. }
  322. CFRelease(fonts);
  323. }
  324. Vector<String> ret;
  325. for (const String &E : font_names) {
  326. ret.push_back(E);
  327. }
  328. return ret;
  329. }
  330. String OS_MacOS::_get_default_fontname(const String &p_font_name) const {
  331. String font_name = p_font_name;
  332. if (font_name.to_lower() == "sans-serif") {
  333. font_name = "Helvetica";
  334. } else if (font_name.to_lower() == "serif") {
  335. font_name = "Times";
  336. } else if (font_name.to_lower() == "monospace") {
  337. font_name = "Courier";
  338. } else if (font_name.to_lower() == "fantasy") {
  339. font_name = "Papyrus";
  340. } else if (font_name.to_lower() == "cursive") {
  341. font_name = "Apple Chancery";
  342. };
  343. return font_name;
  344. }
  345. CGFloat OS_MacOS::_weight_to_ct(int p_weight) const {
  346. if (p_weight < 150) {
  347. return -0.80;
  348. } else if (p_weight < 250) {
  349. return -0.60;
  350. } else if (p_weight < 350) {
  351. return -0.40;
  352. } else if (p_weight < 450) {
  353. return 0.0;
  354. } else if (p_weight < 550) {
  355. return 0.23;
  356. } else if (p_weight < 650) {
  357. return 0.30;
  358. } else if (p_weight < 750) {
  359. return 0.40;
  360. } else if (p_weight < 850) {
  361. return 0.56;
  362. } else if (p_weight < 925) {
  363. return 0.62;
  364. } else {
  365. return 1.00;
  366. }
  367. }
  368. CGFloat OS_MacOS::_stretch_to_ct(int p_stretch) const {
  369. if (p_stretch < 56) {
  370. return -0.5;
  371. } else if (p_stretch < 69) {
  372. return -0.37;
  373. } else if (p_stretch < 81) {
  374. return -0.25;
  375. } else if (p_stretch < 93) {
  376. return -0.13;
  377. } else if (p_stretch < 106) {
  378. return 0.0;
  379. } else if (p_stretch < 137) {
  380. return 0.13;
  381. } else if (p_stretch < 144) {
  382. return 0.25;
  383. } else if (p_stretch < 162) {
  384. return 0.37;
  385. } else {
  386. return 0.5;
  387. }
  388. }
  389. 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 {
  390. Vector<String> ret;
  391. String font_name = _get_default_fontname(p_font_name);
  392. CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, font_name.utf8().get_data(), kCFStringEncodingUTF8);
  393. CTFontSymbolicTraits traits = 0;
  394. if (p_weight >= 700) {
  395. traits |= kCTFontBoldTrait;
  396. }
  397. if (p_italic) {
  398. traits |= kCTFontItalicTrait;
  399. }
  400. if (p_stretch < 100) {
  401. traits |= kCTFontCondensedTrait;
  402. } else if (p_stretch > 100) {
  403. traits |= kCTFontExpandedTrait;
  404. }
  405. CFNumberRef sym_traits = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &traits);
  406. CFMutableDictionaryRef traits_dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
  407. CFDictionaryAddValue(traits_dict, kCTFontSymbolicTrait, sym_traits);
  408. CGFloat weight = _weight_to_ct(p_weight);
  409. CFNumberRef font_weight = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &weight);
  410. CFDictionaryAddValue(traits_dict, kCTFontWeightTrait, font_weight);
  411. CGFloat stretch = _stretch_to_ct(p_stretch);
  412. CFNumberRef font_stretch = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &stretch);
  413. CFDictionaryAddValue(traits_dict, kCTFontWidthTrait, font_stretch);
  414. CFMutableDictionaryRef attributes = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
  415. CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, name);
  416. CFDictionaryAddValue(attributes, kCTFontTraitsAttribute, traits_dict);
  417. CTFontDescriptorRef font = CTFontDescriptorCreateWithAttributes(attributes);
  418. if (font) {
  419. CTFontRef family = CTFontCreateWithFontDescriptor(font, 0, nullptr);
  420. CFStringRef string = CFStringCreateWithCString(kCFAllocatorDefault, p_text.utf8().get_data(), kCFStringEncodingUTF8);
  421. CFRange range = CFRangeMake(0, CFStringGetLength(string));
  422. CTFontRef fallback_family = CTFontCreateForString(family, string, range);
  423. if (fallback_family) {
  424. CTFontDescriptorRef fallback_font = CTFontCopyFontDescriptor(fallback_family);
  425. if (fallback_font) {
  426. CFURLRef url = (CFURLRef)CTFontDescriptorCopyAttribute(fallback_font, kCTFontURLAttribute);
  427. if (url) {
  428. NSString *font_path = [NSString stringWithString:[(__bridge NSURL *)url path]];
  429. ret.push_back(String::utf8([font_path UTF8String]));
  430. CFRelease(url);
  431. }
  432. CFRelease(fallback_font);
  433. }
  434. CFRelease(fallback_family);
  435. }
  436. CFRelease(string);
  437. CFRelease(font);
  438. }
  439. CFRelease(attributes);
  440. CFRelease(traits_dict);
  441. CFRelease(sym_traits);
  442. CFRelease(font_stretch);
  443. CFRelease(font_weight);
  444. CFRelease(name);
  445. return ret;
  446. }
  447. String OS_MacOS::get_system_font_path(const String &p_font_name, int p_weight, int p_stretch, bool p_italic) const {
  448. String ret;
  449. String font_name = _get_default_fontname(p_font_name);
  450. CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, font_name.utf8().get_data(), kCFStringEncodingUTF8);
  451. CTFontSymbolicTraits traits = 0;
  452. if (p_weight > 700) {
  453. traits |= kCTFontBoldTrait;
  454. }
  455. if (p_italic) {
  456. traits |= kCTFontItalicTrait;
  457. }
  458. if (p_stretch < 100) {
  459. traits |= kCTFontCondensedTrait;
  460. } else if (p_stretch > 100) {
  461. traits |= kCTFontExpandedTrait;
  462. }
  463. CFNumberRef sym_traits = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &traits);
  464. CFMutableDictionaryRef traits_dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
  465. CFDictionaryAddValue(traits_dict, kCTFontSymbolicTrait, sym_traits);
  466. CGFloat weight = _weight_to_ct(p_weight);
  467. CFNumberRef font_weight = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &weight);
  468. CFDictionaryAddValue(traits_dict, kCTFontWeightTrait, font_weight);
  469. CGFloat stretch = _stretch_to_ct(p_stretch);
  470. CFNumberRef font_stretch = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &stretch);
  471. CFDictionaryAddValue(traits_dict, kCTFontWidthTrait, font_stretch);
  472. CFMutableDictionaryRef attributes = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
  473. CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, name);
  474. CFDictionaryAddValue(attributes, kCTFontTraitsAttribute, traits_dict);
  475. CTFontDescriptorRef font = CTFontDescriptorCreateWithAttributes(attributes);
  476. if (font) {
  477. CFURLRef url = (CFURLRef)CTFontDescriptorCopyAttribute(font, kCTFontURLAttribute);
  478. if (url) {
  479. NSString *font_path = [NSString stringWithString:[(__bridge NSURL *)url path]];
  480. ret = String::utf8([font_path UTF8String]);
  481. CFRelease(url);
  482. }
  483. CFRelease(font);
  484. }
  485. CFRelease(attributes);
  486. CFRelease(traits_dict);
  487. CFRelease(sym_traits);
  488. CFRelease(font_stretch);
  489. CFRelease(font_weight);
  490. CFRelease(name);
  491. return ret;
  492. }
  493. String OS_MacOS::get_executable_path() const {
  494. char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
  495. int pid = getpid();
  496. pid_t ret = proc_pidpath(pid, pathbuf, sizeof(pathbuf));
  497. if (ret <= 0) {
  498. return OS::get_executable_path();
  499. } else {
  500. String path;
  501. path.parse_utf8(pathbuf);
  502. return path;
  503. }
  504. }
  505. Error OS_MacOS::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
  506. // Use NSWorkspace if path is an .app bundle.
  507. NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
  508. NSBundle *bundle = [NSBundle bundleWithURL:url];
  509. if (bundle) {
  510. NSMutableArray *arguments = [[NSMutableArray alloc] init];
  511. for (const String &arg : p_arguments) {
  512. [arguments addObject:[NSString stringWithUTF8String:arg.utf8().get_data()]];
  513. }
  514. #if defined(__x86_64__)
  515. if (@available(macOS 10.15, *)) {
  516. #endif
  517. NSWorkspaceOpenConfiguration *configuration = [[NSWorkspaceOpenConfiguration alloc] init];
  518. [configuration setArguments:arguments];
  519. [configuration setCreatesNewApplicationInstance:YES];
  520. __block dispatch_semaphore_t lock = dispatch_semaphore_create(0);
  521. __block Error err = ERR_TIMEOUT;
  522. __block pid_t pid = 0;
  523. [[NSWorkspace sharedWorkspace] openApplicationAtURL:url
  524. configuration:configuration
  525. completionHandler:^(NSRunningApplication *app, NSError *error) {
  526. if (error) {
  527. err = ERR_CANT_FORK;
  528. NSLog(@"Failed to execute: %@", error.localizedDescription);
  529. } else {
  530. pid = [app processIdentifier];
  531. err = OK;
  532. }
  533. dispatch_semaphore_signal(lock);
  534. }];
  535. dispatch_semaphore_wait(lock, dispatch_time(DISPATCH_TIME_NOW, 20000000000)); // 20 sec timeout, wait for app to launch.
  536. if (err == OK) {
  537. if (r_child_id) {
  538. *r_child_id = (ProcessID)pid;
  539. }
  540. }
  541. return err;
  542. #if defined(__x86_64__)
  543. } else {
  544. Error err = ERR_TIMEOUT;
  545. NSError *error = nullptr;
  546. NSRunningApplication *app = [[NSWorkspace sharedWorkspace] launchApplicationAtURL:url options:NSWorkspaceLaunchNewInstance configuration:[NSDictionary dictionaryWithObject:arguments forKey:NSWorkspaceLaunchConfigurationArguments] error:&error];
  547. if (error) {
  548. err = ERR_CANT_FORK;
  549. NSLog(@"Failed to execute: %@", error.localizedDescription);
  550. } else {
  551. if (r_child_id) {
  552. *r_child_id = (ProcessID)[app processIdentifier];
  553. }
  554. err = OK;
  555. }
  556. return err;
  557. }
  558. #endif
  559. } else {
  560. return OS_Unix::create_process(p_path, p_arguments, r_child_id, p_open_console);
  561. }
  562. }
  563. Error OS_MacOS::create_instance(const List<String> &p_arguments, ProcessID *r_child_id) {
  564. // If executable is bundled, always execute editor instances as an app bundle to ensure app window is registered and activated correctly.
  565. NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  566. if (nsappname != nil) {
  567. String path;
  568. path.parse_utf8([[[NSBundle mainBundle] bundlePath] UTF8String]);
  569. return create_process(path, p_arguments, r_child_id, false);
  570. } else {
  571. return create_process(get_executable_path(), p_arguments, r_child_id, false);
  572. }
  573. }
  574. String OS_MacOS::get_unique_id() const {
  575. static String serial_number;
  576. if (serial_number.is_empty()) {
  577. io_service_t platform_expert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"));
  578. CFStringRef serial_number_cf_string = nullptr;
  579. if (platform_expert) {
  580. serial_number_cf_string = (CFStringRef)IORegistryEntryCreateCFProperty(platform_expert, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0);
  581. IOObjectRelease(platform_expert);
  582. }
  583. NSString *serial_number_ns_string = nil;
  584. if (serial_number_cf_string) {
  585. serial_number_ns_string = [NSString stringWithString:(__bridge NSString *)serial_number_cf_string];
  586. CFRelease(serial_number_cf_string);
  587. }
  588. if (serial_number_ns_string) {
  589. serial_number.parse_utf8([serial_number_ns_string UTF8String]);
  590. }
  591. }
  592. return serial_number;
  593. }
  594. bool OS_MacOS::_check_internal_feature_support(const String &p_feature) {
  595. if (p_feature == "system_fonts") {
  596. return true;
  597. }
  598. if (p_feature == "pc") {
  599. return true;
  600. }
  601. return false;
  602. }
  603. void OS_MacOS::disable_crash_handler() {
  604. crash_handler.disable();
  605. }
  606. bool OS_MacOS::is_disable_crash_handler() const {
  607. return crash_handler.is_disabled();
  608. }
  609. Error OS_MacOS::move_to_trash(const String &p_path) {
  610. NSFileManager *fm = [NSFileManager defaultManager];
  611. NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
  612. NSError *err;
  613. if (![fm trashItemAtURL:url resultingItemURL:nil error:&err]) {
  614. ERR_PRINT("trashItemAtURL error: " + String::utf8(err.localizedDescription.UTF8String));
  615. return FAILED;
  616. }
  617. return OK;
  618. }
  619. String OS_MacOS::get_system_ca_certificates() {
  620. CFArrayRef result;
  621. SecCertificateRef item;
  622. CFDataRef der;
  623. OSStatus ret = SecTrustCopyAnchorCertificates(&result);
  624. ERR_FAIL_COND_V(ret != noErr, "");
  625. CFIndex l = CFArrayGetCount(result);
  626. String certs;
  627. PackedByteArray pba;
  628. for (CFIndex i = 0; i < l; i++) {
  629. item = (SecCertificateRef)CFArrayGetValueAtIndex(result, i);
  630. der = SecCertificateCopyData(item);
  631. int derlen = CFDataGetLength(der);
  632. if (pba.size() < derlen * 3) {
  633. pba.resize(derlen * 3);
  634. }
  635. size_t b64len = 0;
  636. Error err = CryptoCore::b64_encode(pba.ptrw(), pba.size(), &b64len, (unsigned char *)CFDataGetBytePtr(der), derlen);
  637. CFRelease(der);
  638. ERR_CONTINUE(err != OK);
  639. certs += "-----BEGIN CERTIFICATE-----\n" + String((char *)pba.ptr(), b64len) + "\n-----END CERTIFICATE-----\n";
  640. }
  641. CFRelease(result);
  642. return certs;
  643. }
  644. OS::PreferredTextureFormat OS_MacOS::get_preferred_texture_format() const {
  645. // macOS supports both formats on ARM. Prefer S3TC/BPTC
  646. // for better compatibility with x86 platforms.
  647. return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC;
  648. }
  649. void OS_MacOS::run() {
  650. if (!main_loop) {
  651. return;
  652. }
  653. @autoreleasepool {
  654. main_loop->initialize();
  655. }
  656. bool quit = false;
  657. while (!quit) {
  658. @autoreleasepool {
  659. @try {
  660. if (DisplayServer::get_singleton()) {
  661. DisplayServer::get_singleton()->process_events(); // Get rid of pending events.
  662. }
  663. joypad_macos->start_processing();
  664. if (Main::iteration()) {
  665. quit = true;
  666. }
  667. } @catch (NSException *exception) {
  668. ERR_PRINT("NSException: " + String::utf8([exception reason].UTF8String));
  669. }
  670. }
  671. }
  672. main_loop->finalize();
  673. }
  674. OS_MacOS::OS_MacOS() {
  675. if (is_sandboxed()) {
  676. // Load security-scoped bookmarks, request access, remove stale or invalid bookmarks.
  677. NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"];
  678. NSMutableArray *new_bookmarks = [[NSMutableArray alloc] init];
  679. for (id bookmark in bookmarks) {
  680. NSError *error = nil;
  681. BOOL isStale = NO;
  682. NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
  683. if (!error && !isStale) {
  684. if ([url startAccessingSecurityScopedResource]) {
  685. [new_bookmarks addObject:bookmark];
  686. }
  687. }
  688. }
  689. [[NSUserDefaults standardUserDefaults] setObject:new_bookmarks forKey:@"sec_bookmarks"];
  690. }
  691. main_loop = nullptr;
  692. Vector<Logger *> loggers;
  693. loggers.push_back(memnew(MacOSTerminalLogger));
  694. _set_logger(memnew(CompositeLogger(loggers)));
  695. #ifdef COREAUDIO_ENABLED
  696. AudioDriverManager::add_driver(&audio_driver);
  697. #endif
  698. DisplayServerMacOS::register_macos_driver();
  699. // Implicitly create shared NSApplication instance.
  700. [GodotApplication sharedApplication];
  701. // In case we are unbundled, make us a proper UI application.
  702. [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
  703. // Menu bar setup must go between sharedApplication above and
  704. // finishLaunching below, in order to properly emulate the behavior
  705. // of NSApplicationMain.
  706. NSMenu *main_menu = [[NSMenu alloc] initWithTitle:@""];
  707. [NSApp setMainMenu:main_menu];
  708. [NSApp finishLaunching];
  709. id delegate = [[GodotApplicationDelegate alloc] init];
  710. ERR_FAIL_NULL(delegate);
  711. [NSApp setDelegate:delegate];
  712. [NSApp registerUserInterfaceItemSearchHandler:delegate];
  713. pre_wait_observer = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, true, 0, &pre_wait_observer_cb, nullptr);
  714. CFRunLoopAddObserver(CFRunLoopGetCurrent(), pre_wait_observer, kCFRunLoopCommonModes);
  715. // Process application:openFile: event.
  716. while (true) {
  717. NSEvent *event = [NSApp
  718. nextEventMatchingMask:NSEventMaskAny
  719. untilDate:[NSDate distantPast]
  720. inMode:NSDefaultRunLoopMode
  721. dequeue:YES];
  722. if (event == nil) {
  723. break;
  724. }
  725. [NSApp sendEvent:event];
  726. }
  727. [NSApp activateIgnoringOtherApps:YES];
  728. }
  729. OS_MacOS::~OS_MacOS() {
  730. CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), pre_wait_observer, kCFRunLoopCommonModes);
  731. CFRelease(pre_wait_observer);
  732. }