os_macos.mm 25 KB

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