os_osx.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /*************************************************************************/
  2. /* os_osx.mm */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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_osx.h"
  31. #include "core/version_generated.gen.h"
  32. #include "dir_access_osx.h"
  33. #include "display_server_osx.h"
  34. #include "main/main.h"
  35. #include <dlfcn.h>
  36. #include <libproc.h>
  37. #include <mach-o/dyld.h>
  38. #include <os/log.h>
  39. /*************************************************************************/
  40. /* OSXTerminalLogger */
  41. /*************************************************************************/
  42. class OSXTerminalLogger : public StdLogger {
  43. public:
  44. virtual void log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type = ERR_ERROR) {
  45. if (!should_log(true)) {
  46. return;
  47. }
  48. const char *err_details;
  49. if (p_rationale && p_rationale[0])
  50. err_details = p_rationale;
  51. else
  52. err_details = p_code;
  53. switch (p_type) {
  54. case ERR_WARNING:
  55. os_log_info(OS_LOG_DEFAULT,
  56. "WARNING: %{public}s\nat: %{public}s (%{public}s:%i)",
  57. err_details, p_function, p_file, p_line);
  58. logf_error("\E[1;33mWARNING:\E[0;93m %s\n", err_details);
  59. logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
  60. break;
  61. case ERR_SCRIPT:
  62. os_log_error(OS_LOG_DEFAULT,
  63. "SCRIPT ERROR: %{public}s\nat: %{public}s (%{public}s:%i)",
  64. err_details, p_function, p_file, p_line);
  65. logf_error("\E[1;35mSCRIPT ERROR:\E[0;95m %s\n", err_details);
  66. logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
  67. break;
  68. case ERR_SHADER:
  69. os_log_error(OS_LOG_DEFAULT,
  70. "SHADER ERROR: %{public}s\nat: %{public}s (%{public}s:%i)",
  71. err_details, p_function, p_file, p_line);
  72. logf_error("\E[1;36mSHADER ERROR:\E[0;96m %s\n", err_details);
  73. logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
  74. break;
  75. case ERR_ERROR:
  76. default:
  77. os_log_error(OS_LOG_DEFAULT,
  78. "ERROR: %{public}s\nat: %{public}s (%{public}s:%i)",
  79. err_details, p_function, p_file, p_line);
  80. logf_error("\E[1;31mERROR:\E[0;91m %s\n", err_details);
  81. logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
  82. break;
  83. }
  84. }
  85. };
  86. /*************************************************************************/
  87. /* OS_OSX */
  88. /*************************************************************************/
  89. String OS_OSX::get_unique_id() const {
  90. static String serial_number;
  91. if (serial_number.is_empty()) {
  92. io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"));
  93. CFStringRef serialNumberAsCFString = NULL;
  94. if (platformExpert) {
  95. serialNumberAsCFString = (CFStringRef)IORegistryEntryCreateCFProperty(platformExpert, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0);
  96. IOObjectRelease(platformExpert);
  97. }
  98. NSString *serialNumberAsNSString = nil;
  99. if (serialNumberAsCFString) {
  100. serialNumberAsNSString = [NSString stringWithString:(NSString *)serialNumberAsCFString];
  101. CFRelease(serialNumberAsCFString);
  102. }
  103. serial_number = [serialNumberAsNSString UTF8String];
  104. }
  105. return serial_number;
  106. }
  107. void OS_OSX::initialize_core() {
  108. OS_Unix::initialize_core();
  109. DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_RESOURCES);
  110. DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_USERDATA);
  111. DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_FILESYSTEM);
  112. }
  113. void OS_OSX::initialize_joypads() {
  114. joypad_osx = memnew(JoypadOSX(Input::get_singleton()));
  115. }
  116. void OS_OSX::initialize() {
  117. crash_handler.initialize();
  118. initialize_core();
  119. //ensure_user_data_dir();
  120. }
  121. void OS_OSX::finalize() {
  122. #ifdef COREMIDI_ENABLED
  123. midi_driver.close();
  124. #endif
  125. delete_main_loop();
  126. if (joypad_osx) {
  127. memdelete(joypad_osx);
  128. }
  129. }
  130. void OS_OSX::set_main_loop(MainLoop *p_main_loop) {
  131. main_loop = p_main_loop;
  132. }
  133. void OS_OSX::delete_main_loop() {
  134. if (!main_loop)
  135. return;
  136. memdelete(main_loop);
  137. main_loop = NULL;
  138. }
  139. String OS_OSX::get_name() const {
  140. return "macOS";
  141. }
  142. Error OS_OSX::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  143. String path = p_path;
  144. if (!FileAccess::exists(path)) {
  145. //this code exists so gdnative can load .dylib files from within the executable path
  146. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  147. }
  148. if (!FileAccess::exists(path)) {
  149. //this code exists so gdnative can load .dylib files from a standard macOS location
  150. path = get_executable_path().get_base_dir().plus_file("../Frameworks").plus_file(p_path.get_file());
  151. }
  152. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  153. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ", error: " + dlerror() + ".");
  154. return OK;
  155. }
  156. MainLoop *OS_OSX::get_main_loop() const {
  157. return main_loop;
  158. }
  159. String OS_OSX::get_config_path() const {
  160. if (has_environment("XDG_CONFIG_HOME")) {
  161. return get_environment("XDG_CONFIG_HOME");
  162. } else if (has_environment("HOME")) {
  163. return get_environment("HOME").plus_file("Library/Application Support");
  164. } else {
  165. return ".";
  166. }
  167. }
  168. String OS_OSX::get_data_path() const {
  169. if (has_environment("XDG_DATA_HOME")) {
  170. return get_environment("XDG_DATA_HOME");
  171. } else {
  172. return get_config_path();
  173. }
  174. }
  175. String OS_OSX::get_cache_path() const {
  176. if (has_environment("XDG_CACHE_HOME")) {
  177. return get_environment("XDG_CACHE_HOME");
  178. } else if (has_environment("HOME")) {
  179. return get_environment("HOME").plus_file("Library/Caches");
  180. } else {
  181. return get_config_path();
  182. }
  183. }
  184. String OS_OSX::get_bundle_resource_dir() const {
  185. NSBundle *main = [NSBundle mainBundle];
  186. NSString *resourcePath = [main resourcePath];
  187. char *utfs = strdup([resourcePath UTF8String]);
  188. String ret;
  189. ret.parse_utf8(utfs);
  190. free(utfs);
  191. return ret;
  192. }
  193. // Get properly capitalized engine name for system paths
  194. String OS_OSX::get_godot_dir_name() const {
  195. return String(VERSION_SHORT_NAME).capitalize();
  196. }
  197. String OS_OSX::get_system_dir(SystemDir p_dir) const {
  198. NSSearchPathDirectory id;
  199. bool found = true;
  200. switch (p_dir) {
  201. case SYSTEM_DIR_DESKTOP: {
  202. id = NSDesktopDirectory;
  203. } break;
  204. case SYSTEM_DIR_DOCUMENTS: {
  205. id = NSDocumentDirectory;
  206. } break;
  207. case SYSTEM_DIR_DOWNLOADS: {
  208. id = NSDownloadsDirectory;
  209. } break;
  210. case SYSTEM_DIR_MOVIES: {
  211. id = NSMoviesDirectory;
  212. } break;
  213. case SYSTEM_DIR_MUSIC: {
  214. id = NSMusicDirectory;
  215. } break;
  216. case SYSTEM_DIR_PICTURES: {
  217. id = NSPicturesDirectory;
  218. } break;
  219. default: {
  220. found = false;
  221. }
  222. }
  223. String ret;
  224. if (found) {
  225. NSArray *paths = NSSearchPathForDirectoriesInDomains(id, NSUserDomainMask, YES);
  226. if (paths && [paths count] >= 1) {
  227. char *utfs = strdup([[paths firstObject] UTF8String]);
  228. ret.parse_utf8(utfs);
  229. free(utfs);
  230. }
  231. }
  232. return ret;
  233. }
  234. Error OS_OSX::shell_open(String p_uri) {
  235. NSString *string = [NSString stringWithUTF8String:p_uri.utf8().get_data()];
  236. NSURL *uri = [[NSURL alloc] initWithString:string];
  237. // Escape special characters in filenames
  238. if (!uri || !uri.scheme || [uri.scheme isEqual:@"file"]) {
  239. uri = [[NSURL alloc] initWithString:[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
  240. }
  241. [[NSWorkspace sharedWorkspace] openURL:uri];
  242. return OK;
  243. }
  244. String OS_OSX::get_locale() const {
  245. NSString *locale_code = [[NSLocale preferredLanguages] objectAtIndex:0];
  246. return String([locale_code UTF8String]).replace("-", "_");
  247. }
  248. String OS_OSX::get_executable_path() const {
  249. int ret;
  250. pid_t pid;
  251. char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
  252. pid = getpid();
  253. ret = proc_pidpath(pid, pathbuf, sizeof(pathbuf));
  254. if (ret <= 0) {
  255. return OS::get_executable_path();
  256. } else {
  257. String path;
  258. path.parse_utf8(pathbuf);
  259. return path;
  260. }
  261. }
  262. void OS_OSX::run() {
  263. force_quit = false;
  264. if (!main_loop)
  265. return;
  266. main_loop->initialize();
  267. bool quit = false;
  268. while (!force_quit && !quit) {
  269. @try {
  270. if (DisplayServer::get_singleton()) {
  271. DisplayServer::get_singleton()->process_events(); // get rid of pending events
  272. }
  273. joypad_osx->process_joypads();
  274. if (Main::iteration()) {
  275. quit = true;
  276. }
  277. } @catch (NSException *exception) {
  278. ERR_PRINT("NSException: " + String([exception reason].UTF8String));
  279. }
  280. };
  281. main_loop->finalize();
  282. }
  283. Error OS_OSX::move_to_trash(const String &p_path) {
  284. NSFileManager *fm = [NSFileManager defaultManager];
  285. NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
  286. NSError *err;
  287. if (![fm trashItemAtURL:url resultingItemURL:nil error:&err]) {
  288. ERR_PRINT("trashItemAtURL error: " + String(err.localizedDescription.UTF8String));
  289. return FAILED;
  290. }
  291. return OK;
  292. }
  293. OS_OSX::OS_OSX() {
  294. main_loop = NULL;
  295. force_quit = false;
  296. Vector<Logger *> loggers;
  297. loggers.push_back(memnew(OSXTerminalLogger));
  298. _set_logger(memnew(CompositeLogger(loggers)));
  299. #ifdef COREAUDIO_ENABLED
  300. AudioDriverManager::add_driver(&audio_driver);
  301. #endif
  302. DisplayServerOSX::register_osx_driver();
  303. }
  304. bool OS_OSX::_check_internal_feature_support(const String &p_feature) {
  305. return p_feature == "pc";
  306. }
  307. void OS_OSX::disable_crash_handler() {
  308. crash_handler.disable();
  309. }
  310. bool OS_OSX::is_disable_crash_handler() const {
  311. return crash_handler.is_disabled();
  312. }