os_macos.mm 29 KB

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