os_macos.mm 28 KB

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