os_macos.mm 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  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. #import "os_macos.h"
  31. #import "dir_access_macos.h"
  32. #ifdef DEBUG_ENABLED
  33. #import "display_server_embedded.h"
  34. #endif
  35. #import "display_server_macos.h"
  36. #import "godot_application.h"
  37. #import "godot_application_delegate.h"
  38. #import "macos_terminal_logger.h"
  39. #include "core/crypto/crypto_core.h"
  40. #include "core/version_generated.gen.h"
  41. #include "main/main.h"
  42. #include <dlfcn.h>
  43. #include <libproc.h>
  44. #import <mach-o/dyld.h>
  45. #include <os/log.h>
  46. #include <sys/sysctl.h>
  47. void OS_MacOS::initialize() {
  48. crash_handler.initialize();
  49. initialize_core();
  50. }
  51. String OS_MacOS::get_model_name() const {
  52. char buffer[256];
  53. size_t buffer_len = 256;
  54. if (sysctlbyname("hw.model", &buffer, &buffer_len, nullptr, 0) == 0 && buffer_len != 0) {
  55. return String::utf8(buffer, buffer_len);
  56. }
  57. return OS_Unix::get_model_name();
  58. }
  59. String OS_MacOS::get_processor_name() const {
  60. char buffer[256];
  61. size_t buffer_len = 256;
  62. if (sysctlbyname("machdep.cpu.brand_string", &buffer, &buffer_len, nullptr, 0) == 0) {
  63. return String::utf8(buffer, buffer_len);
  64. }
  65. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name. Returning an empty string."));
  66. }
  67. bool OS_MacOS::is_sandboxed() const {
  68. return has_environment("APP_SANDBOX_CONTAINER_ID");
  69. }
  70. bool OS_MacOS::request_permission(const String &p_name) {
  71. if (@available(macOS 10.15, *)) {
  72. if (p_name == "macos.permission.RECORD_SCREEN") {
  73. if (CGPreflightScreenCaptureAccess()) {
  74. return true;
  75. } else {
  76. CGRequestScreenCaptureAccess();
  77. return false;
  78. }
  79. }
  80. } else {
  81. if (p_name == "macos.permission.RECORD_SCREEN") {
  82. return true;
  83. }
  84. }
  85. return false;
  86. }
  87. Vector<String> OS_MacOS::get_granted_permissions() const {
  88. Vector<String> ret;
  89. if (@available(macOS 10.15, *)) {
  90. if (CGPreflightScreenCaptureAccess()) {
  91. ret.push_back("macos.permission.RECORD_SCREEN");
  92. }
  93. } else {
  94. ret.push_back("macos.permission.RECORD_SCREEN");
  95. }
  96. if (is_sandboxed()) {
  97. NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"];
  98. for (id bookmark in bookmarks) {
  99. NSError *error = nil;
  100. BOOL isStale = NO;
  101. NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
  102. if (!error && !isStale) {
  103. String url_string = String::utf8([[url path] UTF8String]);
  104. ret.push_back(url_string);
  105. }
  106. }
  107. }
  108. return ret;
  109. }
  110. void OS_MacOS::revoke_granted_permissions() {
  111. if (is_sandboxed()) {
  112. [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"sec_bookmarks"];
  113. }
  114. }
  115. #if TOOLS_ENABLED
  116. // Function to check if a debugger is attached to the current process
  117. bool OS_MacOS::is_debugger_attached() {
  118. int mib[4];
  119. struct kinfo_proc info{};
  120. size_t size = sizeof(info);
  121. // Initialize the flags so that, if sysctl fails, info.kp_proc.p_flag will be 0.
  122. info.kp_proc.p_flag = 0;
  123. // Initialize mib, which tells sysctl the info we want, in this case we're looking for information
  124. // about a specific process ID.
  125. mib[0] = CTL_KERN;
  126. mib[1] = KERN_PROC;
  127. mib[2] = KERN_PROC_PID;
  128. mib[3] = getpid();
  129. if (sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0) {
  130. perror("sysctl");
  131. return false;
  132. }
  133. return (info.kp_proc.p_flag & P_TRACED) != 0;
  134. }
  135. void OS_MacOS::wait_for_debugger(uint32_t p_msec) {
  136. if (p_msec == 0) {
  137. return;
  138. }
  139. CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
  140. CFTimeInterval wait_time = p_msec / 1000.0;
  141. NSTimer *timer = [NSTimer timerWithTimeInterval:0.100
  142. repeats:YES
  143. block:^(NSTimer *t) {
  144. if (is_debugger_attached() || CFAbsoluteTimeGetCurrent() > start + wait_time) {
  145. [NSApp stopModalWithCode:NSModalResponseContinue];
  146. [t invalidate];
  147. }
  148. }];
  149. [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSModalPanelRunLoopMode];
  150. pid_t pid = getpid();
  151. alert(vformat("Attach debugger to pid: %d", pid));
  152. print("continue...");
  153. }
  154. #endif
  155. void OS_MacOS::initialize_core() {
  156. OS_Unix::initialize_core();
  157. DirAccess::make_default<DirAccessMacOS>(DirAccess::ACCESS_RESOURCES);
  158. DirAccess::make_default<DirAccessMacOS>(DirAccess::ACCESS_USERDATA);
  159. DirAccess::make_default<DirAccessMacOS>(DirAccess::ACCESS_FILESYSTEM);
  160. }
  161. void OS_MacOS::finalize() {
  162. if (is_sandboxed()) {
  163. NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"];
  164. for (id bookmark in bookmarks) {
  165. NSError *error = nil;
  166. BOOL isStale = NO;
  167. NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
  168. if (!error && !isStale) {
  169. [url stopAccessingSecurityScopedResource];
  170. }
  171. }
  172. }
  173. #ifdef COREMIDI_ENABLED
  174. midi_driver.close();
  175. #endif
  176. delete_main_loop();
  177. if (joypad_apple) {
  178. memdelete(joypad_apple);
  179. }
  180. }
  181. void OS_MacOS::initialize_joypads() {
  182. joypad_apple = memnew(JoypadApple());
  183. }
  184. void OS_MacOS::set_main_loop(MainLoop *p_main_loop) {
  185. main_loop = p_main_loop;
  186. }
  187. void OS_MacOS::delete_main_loop() {
  188. if (!main_loop) {
  189. return;
  190. }
  191. memdelete(main_loop);
  192. main_loop = nullptr;
  193. }
  194. void OS_MacOS::set_cmdline_platform_args(const List<String> &p_args) {
  195. launch_service_args = p_args;
  196. }
  197. List<String> OS_MacOS::get_cmdline_platform_args() const {
  198. return launch_service_args;
  199. }
  200. String OS_MacOS::get_name() const {
  201. return "macOS";
  202. }
  203. String OS_MacOS::get_distribution_name() const {
  204. return get_name();
  205. }
  206. String OS_MacOS::get_version() const {
  207. NSOperatingSystemVersion ver = [NSProcessInfo processInfo].operatingSystemVersion;
  208. return vformat("%d.%d.%d", (int64_t)ver.majorVersion, (int64_t)ver.minorVersion, (int64_t)ver.patchVersion);
  209. }
  210. String OS_MacOS::get_version_alias() const {
  211. NSOperatingSystemVersion ver = [NSProcessInfo processInfo].operatingSystemVersion;
  212. String macos_string;
  213. if (ver.majorVersion == 15) {
  214. macos_string += "Sequoia";
  215. } else if (ver.majorVersion == 14) {
  216. macos_string += "Sonoma";
  217. } else if (ver.majorVersion == 13) {
  218. macos_string += "Ventura";
  219. } else if (ver.majorVersion == 12) {
  220. macos_string += "Monterey";
  221. } else if (ver.majorVersion == 11 || (ver.majorVersion == 10 && ver.minorVersion == 16)) {
  222. // Big Sur was 10.16 during beta, but it became 11 for the stable version.
  223. macos_string += "Big Sur";
  224. } else if (ver.majorVersion == 10 && ver.minorVersion == 15) {
  225. macos_string += "Catalina";
  226. } else if (ver.majorVersion == 10 && ver.minorVersion == 14) {
  227. macos_string += "Mojave";
  228. } else if (ver.majorVersion == 10 && ver.minorVersion == 13) {
  229. macos_string += "High Sierra";
  230. } else {
  231. macos_string += "Unknown";
  232. }
  233. // macOS versions older than 10.13 cannot run Godot.
  234. return vformat("%s (%s)", macos_string, get_version());
  235. }
  236. void OS_MacOS::alert(const String &p_alert, const String &p_title) {
  237. NSAlert *window = [[NSAlert alloc] init];
  238. NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
  239. NSString *ns_alert = [NSString stringWithUTF8String:p_alert.utf8().get_data()];
  240. NSTextField *text_field = [NSTextField labelWithString:ns_alert];
  241. [text_field setAlignment:NSTextAlignmentCenter];
  242. [window addButtonWithTitle:@"OK"];
  243. [window setMessageText:ns_title];
  244. [window setAccessoryView:text_field];
  245. [window setAlertStyle:NSAlertStyleWarning];
  246. id key_window = [[NSApplication sharedApplication] keyWindow];
  247. [window runModal];
  248. if (key_window) {
  249. [key_window makeKeyAndOrderFront:nil];
  250. }
  251. }
  252. _FORCE_INLINE_ String OS_MacOS::get_framework_executable(const String &p_path) {
  253. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  254. // Read framework bundle to get executable name.
  255. NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
  256. NSBundle *bundle = [NSBundle bundleWithURL:url];
  257. if (bundle) {
  258. String exe_path = String::utf8([[bundle executablePath] UTF8String]);
  259. if (da->file_exists(exe_path)) {
  260. return exe_path;
  261. }
  262. }
  263. // Try default executable name (invalid framework).
  264. if (da->dir_exists(p_path) && da->file_exists(p_path.path_join(p_path.get_file().get_basename()))) {
  265. return p_path.path_join(p_path.get_file().get_basename());
  266. }
  267. // Not a framework, try loading as .dylib.
  268. return p_path;
  269. }
  270. Error OS_MacOS::open_dynamic_library(const String &p_path, void *&p_library_handle, GDExtensionData *p_data) {
  271. String path = get_framework_executable(p_path);
  272. if (!FileAccess::exists(path)) {
  273. // Load .dylib or framework from within the executable path.
  274. path = get_framework_executable(get_executable_path().get_base_dir().path_join(p_path.get_file()));
  275. }
  276. if (!FileAccess::exists(path)) {
  277. // Load .dylib or framework from a standard macOS location.
  278. path = get_framework_executable(get_executable_path().get_base_dir().path_join("../Frameworks").path_join(p_path.get_file()));
  279. }
  280. if (!FileAccess::exists(path)) {
  281. // Try using path as is. macOS system libraries with `/usr/lib/*` path do not exist as physical files and are loaded from shared cache.
  282. path = p_path;
  283. }
  284. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  285. ERR_FAIL_NULL_V_MSG(p_library_handle, ERR_CANT_OPEN, vformat("Can't open dynamic library: %s. Error: %s.", p_path, dlerror()));
  286. if (p_data != nullptr && p_data->r_resolved_path != nullptr) {
  287. *p_data->r_resolved_path = path;
  288. }
  289. return OK;
  290. }
  291. MainLoop *OS_MacOS::get_main_loop() const {
  292. return main_loop;
  293. }
  294. String OS_MacOS::get_config_path() const {
  295. if (has_environment("HOME")) {
  296. return get_environment("HOME").path_join("Library/Application Support");
  297. }
  298. return ".";
  299. }
  300. String OS_MacOS::get_data_path() const {
  301. return get_config_path();
  302. }
  303. String OS_MacOS::get_cache_path() const {
  304. if (has_environment("HOME")) {
  305. return get_environment("HOME").path_join("Library/Caches");
  306. }
  307. return get_config_path();
  308. }
  309. String OS_MacOS::get_temp_path() const {
  310. static String ret;
  311. if (ret.is_empty()) {
  312. NSURL *url = [NSURL fileURLWithPath:NSTemporaryDirectory()
  313. isDirectory:YES];
  314. if (url) {
  315. ret = String::utf8([url.path UTF8String]);
  316. ret = ret.trim_prefix("file://");
  317. }
  318. }
  319. return ret;
  320. }
  321. String OS_MacOS::get_bundle_resource_dir() const {
  322. String ret;
  323. NSBundle *main = [NSBundle mainBundle];
  324. if (main) {
  325. NSString *resource_path = [main resourcePath];
  326. ret.append_utf8([resource_path UTF8String]);
  327. }
  328. return ret;
  329. }
  330. String OS_MacOS::get_bundle_icon_path() const {
  331. String ret;
  332. NSBundle *main = [NSBundle mainBundle];
  333. if (main) {
  334. NSString *icon_path = [[main infoDictionary] objectForKey:@"CFBundleIconFile"];
  335. if (icon_path) {
  336. ret.append_utf8([icon_path UTF8String]);
  337. }
  338. }
  339. return ret;
  340. }
  341. // Get properly capitalized engine name for system paths
  342. String OS_MacOS::get_godot_dir_name() const {
  343. return String(GODOT_VERSION_SHORT_NAME).capitalize();
  344. }
  345. String OS_MacOS::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  346. NSSearchPathDirectory id;
  347. bool found = true;
  348. switch (p_dir) {
  349. case SYSTEM_DIR_DESKTOP: {
  350. id = NSDesktopDirectory;
  351. } break;
  352. case SYSTEM_DIR_DOCUMENTS: {
  353. id = NSDocumentDirectory;
  354. } break;
  355. case SYSTEM_DIR_DOWNLOADS: {
  356. id = NSDownloadsDirectory;
  357. } break;
  358. case SYSTEM_DIR_MOVIES: {
  359. id = NSMoviesDirectory;
  360. } break;
  361. case SYSTEM_DIR_MUSIC: {
  362. id = NSMusicDirectory;
  363. } break;
  364. case SYSTEM_DIR_PICTURES: {
  365. id = NSPicturesDirectory;
  366. } break;
  367. default: {
  368. found = false;
  369. }
  370. }
  371. String ret;
  372. if (found) {
  373. NSArray *paths = NSSearchPathForDirectoriesInDomains(id, NSUserDomainMask, YES);
  374. if (paths && [paths count] >= 1) {
  375. ret.append_utf8([[paths firstObject] UTF8String]);
  376. }
  377. }
  378. return ret;
  379. }
  380. Error OS_MacOS::shell_show_in_file_manager(String p_path, bool p_open_folder) {
  381. bool open_folder = false;
  382. if (DirAccess::dir_exists_absolute(p_path) && p_open_folder) {
  383. open_folder = true;
  384. }
  385. if (!p_path.begins_with("file://")) {
  386. p_path = String("file://") + p_path;
  387. }
  388. NSString *string = [NSString stringWithUTF8String:p_path.utf8().get_data()];
  389. NSURL *uri = [[NSURL alloc] initWithString:[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
  390. if (open_folder) {
  391. [[NSWorkspace sharedWorkspace] openURL:uri];
  392. } else {
  393. [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[ uri ]];
  394. }
  395. return OK;
  396. }
  397. Error OS_MacOS::shell_open(const String &p_uri) {
  398. NSString *string = [NSString stringWithUTF8String:p_uri.utf8().get_data()];
  399. NSURL *uri = [[NSURL alloc] initWithString:string];
  400. if (!uri || !uri.scheme || [uri.scheme isEqual:@"file"]) {
  401. // No scheme set, assume "file://" and escape special characters.
  402. if (!p_uri.begins_with("file://")) {
  403. string = [NSString stringWithUTF8String:("file://" + p_uri).utf8().get_data()];
  404. }
  405. uri = [[NSURL alloc] initWithString:[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
  406. }
  407. [[NSWorkspace sharedWorkspace] openURL:uri];
  408. return OK;
  409. }
  410. String OS_MacOS::get_locale() const {
  411. NSString *locale_code = [[NSLocale preferredLanguages] objectAtIndex:0];
  412. return String([locale_code UTF8String]).replace_char('-', '_');
  413. }
  414. Vector<String> OS_MacOS::get_system_fonts() const {
  415. HashSet<String> font_names;
  416. CFArrayRef fonts = CTFontManagerCopyAvailableFontFamilyNames();
  417. if (fonts) {
  418. for (CFIndex i = 0; i < CFArrayGetCount(fonts); i++) {
  419. CFStringRef cf_name = (CFStringRef)CFArrayGetValueAtIndex(fonts, i);
  420. if (cf_name && (CFStringGetLength(cf_name) > 0) && (CFStringCompare(cf_name, CFSTR("LastResort"), kCFCompareCaseInsensitive) != kCFCompareEqualTo) && (CFStringGetCharacterAtIndex(cf_name, 0) != '.')) {
  421. NSString *ns_name = (__bridge NSString *)cf_name;
  422. font_names.insert(String::utf8([ns_name UTF8String]));
  423. }
  424. }
  425. CFRelease(fonts);
  426. }
  427. Vector<String> ret;
  428. for (const String &E : font_names) {
  429. ret.push_back(E);
  430. }
  431. return ret;
  432. }
  433. String OS_MacOS::_get_default_fontname(const String &p_font_name) const {
  434. String font_name = p_font_name;
  435. if (font_name.to_lower() == "sans-serif") {
  436. font_name = "Helvetica";
  437. } else if (font_name.to_lower() == "serif") {
  438. font_name = "Times";
  439. } else if (font_name.to_lower() == "monospace") {
  440. font_name = "Courier";
  441. } else if (font_name.to_lower() == "fantasy") {
  442. font_name = "Papyrus";
  443. } else if (font_name.to_lower() == "cursive") {
  444. font_name = "Apple Chancery";
  445. };
  446. return font_name;
  447. }
  448. CGFloat OS_MacOS::_weight_to_ct(int p_weight) const {
  449. if (p_weight < 150) {
  450. return -0.80;
  451. } else if (p_weight < 250) {
  452. return -0.60;
  453. } else if (p_weight < 350) {
  454. return -0.40;
  455. } else if (p_weight < 450) {
  456. return 0.0;
  457. } else if (p_weight < 550) {
  458. return 0.23;
  459. } else if (p_weight < 650) {
  460. return 0.30;
  461. } else if (p_weight < 750) {
  462. return 0.40;
  463. } else if (p_weight < 850) {
  464. return 0.56;
  465. } else if (p_weight < 925) {
  466. return 0.62;
  467. } else {
  468. return 1.00;
  469. }
  470. }
  471. CGFloat OS_MacOS::_stretch_to_ct(int p_stretch) const {
  472. if (p_stretch < 56) {
  473. return -0.5;
  474. } else if (p_stretch < 69) {
  475. return -0.37;
  476. } else if (p_stretch < 81) {
  477. return -0.25;
  478. } else if (p_stretch < 93) {
  479. return -0.13;
  480. } else if (p_stretch < 106) {
  481. return 0.0;
  482. } else if (p_stretch < 137) {
  483. return 0.13;
  484. } else if (p_stretch < 144) {
  485. return 0.25;
  486. } else if (p_stretch < 162) {
  487. return 0.37;
  488. } else {
  489. return 0.5;
  490. }
  491. }
  492. 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 {
  493. Vector<String> ret;
  494. String font_name = _get_default_fontname(p_font_name);
  495. CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, font_name.utf8().get_data(), kCFStringEncodingUTF8);
  496. CTFontSymbolicTraits traits = 0;
  497. if (p_weight >= 700) {
  498. traits |= kCTFontBoldTrait;
  499. }
  500. if (p_italic) {
  501. traits |= kCTFontItalicTrait;
  502. }
  503. if (p_stretch < 100) {
  504. traits |= kCTFontCondensedTrait;
  505. } else if (p_stretch > 100) {
  506. traits |= kCTFontExpandedTrait;
  507. }
  508. CFNumberRef sym_traits = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &traits);
  509. CFMutableDictionaryRef traits_dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
  510. CFDictionaryAddValue(traits_dict, kCTFontSymbolicTrait, sym_traits);
  511. CGFloat weight = _weight_to_ct(p_weight);
  512. CFNumberRef font_weight = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &weight);
  513. CFDictionaryAddValue(traits_dict, kCTFontWeightTrait, font_weight);
  514. CGFloat stretch = _stretch_to_ct(p_stretch);
  515. CFNumberRef font_stretch = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &stretch);
  516. CFDictionaryAddValue(traits_dict, kCTFontWidthTrait, font_stretch);
  517. CFMutableDictionaryRef attributes = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
  518. CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, name);
  519. CFDictionaryAddValue(attributes, kCTFontTraitsAttribute, traits_dict);
  520. CTFontDescriptorRef font = CTFontDescriptorCreateWithAttributes(attributes);
  521. if (font) {
  522. CTFontRef family = CTFontCreateWithFontDescriptor(font, 0, nullptr);
  523. if (family) {
  524. CFStringRef string = CFStringCreateWithCString(kCFAllocatorDefault, p_text.utf8().get_data(), kCFStringEncodingUTF8);
  525. CFRange range = CFRangeMake(0, CFStringGetLength(string));
  526. CTFontRef fallback_family = CTFontCreateForString(family, string, range);
  527. if (fallback_family) {
  528. CTFontDescriptorRef fallback_font = CTFontCopyFontDescriptor(fallback_family);
  529. if (fallback_font) {
  530. CFURLRef url = (CFURLRef)CTFontDescriptorCopyAttribute(fallback_font, kCTFontURLAttribute);
  531. if (url) {
  532. NSString *font_path = [NSString stringWithString:[(__bridge NSURL *)url path]];
  533. ret.push_back(String::utf8([font_path UTF8String]));
  534. CFRelease(url);
  535. }
  536. CFRelease(fallback_font);
  537. }
  538. CFRelease(fallback_family);
  539. }
  540. CFRelease(string);
  541. CFRelease(family);
  542. }
  543. CFRelease(font);
  544. }
  545. CFRelease(attributes);
  546. CFRelease(traits_dict);
  547. CFRelease(sym_traits);
  548. CFRelease(font_stretch);
  549. CFRelease(font_weight);
  550. CFRelease(name);
  551. return ret;
  552. }
  553. String OS_MacOS::get_system_font_path(const String &p_font_name, int p_weight, int p_stretch, bool p_italic) const {
  554. String ret;
  555. String font_name = _get_default_fontname(p_font_name);
  556. CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, font_name.utf8().get_data(), kCFStringEncodingUTF8);
  557. CTFontSymbolicTraits traits = 0;
  558. if (p_weight > 700) {
  559. traits |= kCTFontBoldTrait;
  560. }
  561. if (p_italic) {
  562. traits |= kCTFontItalicTrait;
  563. }
  564. if (p_stretch < 100) {
  565. traits |= kCTFontCondensedTrait;
  566. } else if (p_stretch > 100) {
  567. traits |= kCTFontExpandedTrait;
  568. }
  569. CFNumberRef sym_traits = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &traits);
  570. CFMutableDictionaryRef traits_dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
  571. CFDictionaryAddValue(traits_dict, kCTFontSymbolicTrait, sym_traits);
  572. CGFloat weight = _weight_to_ct(p_weight);
  573. CFNumberRef font_weight = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &weight);
  574. CFDictionaryAddValue(traits_dict, kCTFontWeightTrait, font_weight);
  575. CGFloat stretch = _stretch_to_ct(p_stretch);
  576. CFNumberRef font_stretch = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &stretch);
  577. CFDictionaryAddValue(traits_dict, kCTFontWidthTrait, font_stretch);
  578. CFMutableDictionaryRef attributes = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
  579. CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, name);
  580. CFDictionaryAddValue(attributes, kCTFontTraitsAttribute, traits_dict);
  581. CTFontDescriptorRef font = CTFontDescriptorCreateWithAttributes(attributes);
  582. if (font) {
  583. CFURLRef url = (CFURLRef)CTFontDescriptorCopyAttribute(font, kCTFontURLAttribute);
  584. if (url) {
  585. NSString *font_path = [NSString stringWithString:[(__bridge NSURL *)url path]];
  586. ret = String::utf8([font_path UTF8String]);
  587. CFRelease(url);
  588. }
  589. CFRelease(font);
  590. }
  591. CFRelease(attributes);
  592. CFRelease(traits_dict);
  593. CFRelease(sym_traits);
  594. CFRelease(font_stretch);
  595. CFRelease(font_weight);
  596. CFRelease(name);
  597. return ret;
  598. }
  599. String OS_MacOS::get_executable_path() const {
  600. char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
  601. int pid = getpid();
  602. pid_t ret = proc_pidpath(pid, pathbuf, sizeof(pathbuf));
  603. if (ret <= 0) {
  604. return OS::get_executable_path();
  605. } else {
  606. return String::utf8(pathbuf);
  607. }
  608. }
  609. Error OS_MacOS::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
  610. // Use NSWorkspace if path is an .app bundle.
  611. NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
  612. NSBundle *bundle = [NSBundle bundleWithURL:url];
  613. if (bundle) {
  614. NSMutableArray *arguments = [[NSMutableArray alloc] init];
  615. for (const String &arg : p_arguments) {
  616. [arguments addObject:[NSString stringWithUTF8String:arg.utf8().get_data()]];
  617. }
  618. #if defined(__x86_64__)
  619. if (@available(macOS 10.15, *)) {
  620. #endif
  621. NSWorkspaceOpenConfiguration *configuration = [[NSWorkspaceOpenConfiguration alloc] init];
  622. [configuration setArguments:arguments];
  623. [configuration setCreatesNewApplicationInstance:YES];
  624. __block dispatch_semaphore_t lock = dispatch_semaphore_create(0);
  625. __block Error err = ERR_TIMEOUT;
  626. __block pid_t pid = 0;
  627. [[NSWorkspace sharedWorkspace] openApplicationAtURL:url
  628. configuration:configuration
  629. completionHandler:^(NSRunningApplication *app, NSError *error) {
  630. if (error) {
  631. err = ERR_CANT_FORK;
  632. NSLog(@"Failed to execute: %@", error.localizedDescription);
  633. } else {
  634. pid = [app processIdentifier];
  635. err = OK;
  636. }
  637. dispatch_semaphore_signal(lock);
  638. }];
  639. dispatch_semaphore_wait(lock, dispatch_time(DISPATCH_TIME_NOW, 20000000000)); // 20 sec timeout, wait for app to launch.
  640. if (err == OK) {
  641. if (r_child_id) {
  642. *r_child_id = (ProcessID)pid;
  643. }
  644. }
  645. return err;
  646. #if defined(__x86_64__)
  647. } else {
  648. Error err = ERR_TIMEOUT;
  649. NSError *error = nullptr;
  650. NSRunningApplication *app = [[NSWorkspace sharedWorkspace] launchApplicationAtURL:url options:NSWorkspaceLaunchNewInstance configuration:[NSDictionary dictionaryWithObject:arguments forKey:NSWorkspaceLaunchConfigurationArguments] error:&error];
  651. if (error) {
  652. err = ERR_CANT_FORK;
  653. NSLog(@"Failed to execute: %@", error.localizedDescription);
  654. } else {
  655. if (r_child_id) {
  656. *r_child_id = (ProcessID)[app processIdentifier];
  657. }
  658. err = OK;
  659. }
  660. return err;
  661. }
  662. #endif
  663. } else {
  664. return OS_Unix::create_process(p_path, p_arguments, r_child_id, p_open_console);
  665. }
  666. }
  667. Error OS_MacOS::create_instance(const List<String> &p_arguments, ProcessID *r_child_id) {
  668. // If executable is bundled, always execute editor instances as an app bundle to ensure app window is registered and activated correctly.
  669. NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  670. if (nsappname != nil) {
  671. String path = String::utf8([[[NSBundle mainBundle] bundlePath] UTF8String]);
  672. return create_process(path, p_arguments, r_child_id, false);
  673. } else {
  674. return create_process(get_executable_path(), p_arguments, r_child_id, false);
  675. }
  676. }
  677. bool OS_MacOS::is_process_running(const ProcessID &p_pid) const {
  678. NSRunningApplication *app = [NSRunningApplication runningApplicationWithProcessIdentifier:(pid_t)p_pid];
  679. if (!app) {
  680. return OS_Unix::is_process_running(p_pid);
  681. }
  682. return ![app isTerminated];
  683. }
  684. String OS_MacOS::get_unique_id() const {
  685. static String serial_number;
  686. if (serial_number.is_empty()) {
  687. io_service_t platform_expert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"));
  688. CFStringRef serial_number_cf_string = nullptr;
  689. if (platform_expert) {
  690. serial_number_cf_string = (CFStringRef)IORegistryEntryCreateCFProperty(platform_expert, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0);
  691. IOObjectRelease(platform_expert);
  692. }
  693. NSString *serial_number_ns_string = nil;
  694. if (serial_number_cf_string) {
  695. serial_number_ns_string = [NSString stringWithString:(__bridge NSString *)serial_number_cf_string];
  696. CFRelease(serial_number_cf_string);
  697. }
  698. if (serial_number_ns_string) {
  699. serial_number.append_utf8([serial_number_ns_string UTF8String]);
  700. }
  701. }
  702. return serial_number;
  703. }
  704. bool OS_MacOS::_check_internal_feature_support(const String &p_feature) {
  705. if (p_feature == "system_fonts") {
  706. return true;
  707. }
  708. if (p_feature == "pc") {
  709. return true;
  710. }
  711. return false;
  712. }
  713. void OS_MacOS::disable_crash_handler() {
  714. crash_handler.disable();
  715. }
  716. bool OS_MacOS::is_disable_crash_handler() const {
  717. return crash_handler.is_disabled();
  718. }
  719. Error OS_MacOS::move_to_trash(const String &p_path) {
  720. NSFileManager *fm = [NSFileManager defaultManager];
  721. NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
  722. NSError *err;
  723. if (![fm trashItemAtURL:url resultingItemURL:nil error:&err]) {
  724. ERR_PRINT("trashItemAtURL error: " + String::utf8(err.localizedDescription.UTF8String));
  725. return FAILED;
  726. }
  727. return OK;
  728. }
  729. String OS_MacOS::get_system_ca_certificates() {
  730. CFArrayRef result;
  731. SecCertificateRef item;
  732. CFDataRef der;
  733. OSStatus ret = SecTrustCopyAnchorCertificates(&result);
  734. ERR_FAIL_COND_V(ret != noErr, "");
  735. CFIndex l = CFArrayGetCount(result);
  736. String certs;
  737. PackedByteArray pba;
  738. for (CFIndex i = 0; i < l; i++) {
  739. item = (SecCertificateRef)CFArrayGetValueAtIndex(result, i);
  740. der = SecCertificateCopyData(item);
  741. int derlen = CFDataGetLength(der);
  742. if (pba.size() < derlen * 3) {
  743. pba.resize(derlen * 3);
  744. }
  745. size_t b64len = 0;
  746. Error err = CryptoCore::b64_encode(pba.ptrw(), pba.size(), &b64len, (unsigned char *)CFDataGetBytePtr(der), derlen);
  747. CFRelease(der);
  748. ERR_CONTINUE(err != OK);
  749. // Certificate is bas64 encoded, aka ascii.
  750. certs += "-----BEGIN CERTIFICATE-----\n" + String::ascii(Span((char *)pba.ptr(), b64len)) + "\n-----END CERTIFICATE-----\n";
  751. }
  752. CFRelease(result);
  753. return certs;
  754. }
  755. OS::PreferredTextureFormat OS_MacOS::get_preferred_texture_format() const {
  756. // macOS supports both formats on ARM. Prefer S3TC/BPTC
  757. // for better compatibility with x86 platforms.
  758. return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC;
  759. }
  760. OS_MacOS::OS_MacOS(const char *p_execpath, int p_argc, char **p_argv) {
  761. execpath = p_execpath;
  762. argc = p_argc;
  763. argv = p_argv;
  764. if (is_sandboxed()) {
  765. // Load security-scoped bookmarks, request access, remove stale or invalid bookmarks.
  766. NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"];
  767. NSMutableArray *new_bookmarks = [[NSMutableArray alloc] init];
  768. for (id bookmark in bookmarks) {
  769. NSError *error = nil;
  770. BOOL isStale = NO;
  771. NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
  772. if (!error && !isStale) {
  773. if ([url startAccessingSecurityScopedResource]) {
  774. [new_bookmarks addObject:bookmark];
  775. }
  776. }
  777. }
  778. [[NSUserDefaults standardUserDefaults] setObject:new_bookmarks forKey:@"sec_bookmarks"];
  779. }
  780. Vector<Logger *> loggers;
  781. loggers.push_back(memnew(MacOSTerminalLogger));
  782. _set_logger(memnew(CompositeLogger(loggers)));
  783. #ifdef COREAUDIO_ENABLED
  784. AudioDriverManager::add_driver(&audio_driver);
  785. #endif
  786. DisplayServerMacOS::register_macos_driver();
  787. }
  788. // MARK: - OS_MacOS_NSApp
  789. void OS_MacOS_NSApp::run() {
  790. [NSApp run];
  791. }
  792. static bool sig_received = false;
  793. static void handle_interrupt(int sig) {
  794. if (sig == SIGINT) {
  795. sig_received = true;
  796. }
  797. }
  798. void OS_MacOS_NSApp::start_main() {
  799. Error err;
  800. @autoreleasepool {
  801. err = Main::setup(execpath, argc, argv);
  802. }
  803. if (err == OK) {
  804. main_started = true;
  805. int ret;
  806. @autoreleasepool {
  807. ret = Main::start();
  808. }
  809. if (ret == EXIT_SUCCESS) {
  810. if (main_loop) {
  811. @autoreleasepool {
  812. main_loop->initialize();
  813. }
  814. DisplayServer *ds = DisplayServer::get_singleton();
  815. DisplayServerMacOS *ds_mac = Object::cast_to<DisplayServerMacOS>(ds);
  816. pre_wait_observer = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, true, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
  817. @autoreleasepool {
  818. @try {
  819. if (ds_mac) {
  820. ds_mac->_process_events(false);
  821. } else if (ds) {
  822. ds->process_events();
  823. }
  824. joypad_apple->process_joypads();
  825. if (Main::iteration() || sig_received) {
  826. terminate();
  827. }
  828. } @catch (NSException *exception) {
  829. ERR_PRINT("NSException: " + String::utf8([exception reason].UTF8String));
  830. }
  831. }
  832. CFRunLoopWakeUp(CFRunLoopGetCurrent()); // Prevent main loop from sleeping.
  833. });
  834. CFRunLoopAddObserver(CFRunLoopGetCurrent(), pre_wait_observer, kCFRunLoopCommonModes);
  835. return;
  836. }
  837. } else {
  838. set_exit_code(EXIT_FAILURE);
  839. }
  840. } else if (err == ERR_HELP) { // Returned by --help and --version, so success.
  841. set_exit_code(EXIT_SUCCESS);
  842. } else {
  843. set_exit_code(EXIT_FAILURE);
  844. }
  845. terminate();
  846. }
  847. void OS_MacOS_NSApp::terminate() {
  848. if (pre_wait_observer) {
  849. CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), pre_wait_observer, kCFRunLoopCommonModes);
  850. CFRelease(pre_wait_observer);
  851. pre_wait_observer = nil;
  852. }
  853. should_terminate = true;
  854. [NSApp terminate:nil];
  855. }
  856. void OS_MacOS_NSApp::cleanup() {
  857. if (main_loop) {
  858. main_loop->finalize();
  859. }
  860. if (main_started) {
  861. @autoreleasepool {
  862. Main::cleanup();
  863. }
  864. }
  865. }
  866. OS_MacOS_NSApp::OS_MacOS_NSApp(const char *p_execpath, int p_argc, char **p_argv) :
  867. OS_MacOS(p_execpath, p_argc, p_argv) {
  868. // Implicitly create shared NSApplication instance.
  869. [GodotApplication sharedApplication];
  870. // In case we are unbundled, make us a proper UI application.
  871. [NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];
  872. // Menu bar setup must go between sharedApplication above and
  873. // finishLaunching below, in order to properly emulate the behavior
  874. // of NSApplicationMain.
  875. NSMenu *main_menu = [[NSMenu alloc] initWithTitle:@""];
  876. [NSApp setMainMenu:main_menu];
  877. delegate = [[GodotApplicationDelegate alloc] initWithOS:this];
  878. ERR_FAIL_NULL(delegate);
  879. [NSApp setDelegate:delegate];
  880. [NSApp registerUserInterfaceItemSearchHandler:delegate];
  881. struct sigaction action;
  882. memset(&action, 0, sizeof(action));
  883. action.sa_handler = handle_interrupt;
  884. sigaction(SIGINT, &action, nullptr);
  885. }
  886. // MARK: - OS_MacOS_Embedded
  887. #ifdef DEBUG_ENABLED
  888. void OS_MacOS_Embedded::run() {
  889. CFRunLoopGetCurrent();
  890. @autoreleasepool {
  891. Error err = Main::setup(execpath, argc, argv);
  892. if (err != OK) {
  893. if (err == ERR_HELP) {
  894. return set_exit_code(EXIT_SUCCESS);
  895. }
  896. return set_exit_code(EXIT_FAILURE);
  897. }
  898. }
  899. int ret;
  900. @autoreleasepool {
  901. ret = Main::start();
  902. }
  903. DisplayServerEmbedded *ds = Object::cast_to<DisplayServerEmbedded>(DisplayServer::get_singleton());
  904. if (!ds) {
  905. ERR_FAIL_MSG("DisplayServerEmbedded is not initialized.");
  906. }
  907. if (ds && ret == EXIT_SUCCESS && main_loop) {
  908. @autoreleasepool {
  909. main_loop->initialize();
  910. }
  911. while (true) {
  912. @autoreleasepool {
  913. @try {
  914. ds->process_events();
  915. if (Main::iteration()) {
  916. break;
  917. }
  918. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, 0);
  919. } @catch (NSException *exception) {
  920. ERR_PRINT("NSException: " + String::utf8([exception reason].UTF8String));
  921. }
  922. }
  923. }
  924. main_loop->finalize();
  925. }
  926. Main::cleanup();
  927. }
  928. OS_MacOS_Embedded::OS_MacOS_Embedded(const char *p_execpath, int p_argc, char **p_argv) :
  929. OS_MacOS(p_execpath, p_argc, p_argv) {
  930. DisplayServerEmbedded::register_embedded_driver();
  931. }
  932. #endif