os_macos.mm 23 KB

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