2014-02-10 02:10:30 +01:00
/*************************************************************************/
/* os_osx.mm */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
2017-08-27 14:16:55 +02:00
/* https://godotengine.org */
2014-02-10 02:10:30 +01:00
/*************************************************************************/
2022-01-03 21:27:34 +01:00
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
2014-02-10 02:10:30 +01:00
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
2018-01-05 00:50:27 +01:00
2017-04-09 14:18:49 +02:00
#include "os_osx.h"
2018-09-11 18:13:45 +02:00
#include "core/version_generated.gen.h"
2019-06-22 18:34:26 +02:00
2020-03-07 17:02:54 +01:00
#include "dir_access_osx.h"
#include "display_server_osx.h"
2017-04-09 14:18:49 +02:00
#include "main/main.h"
2019-06-22 18:34:26 +02:00
2018-01-04 20:36:44 +01:00
#include <dlfcn.h>
2017-04-09 14:18:49 +02:00
#include <libproc.h>
2020-03-07 17:02:54 +01:00
#include <mach-o/dyld.h>
#include <os/log.h>
2017-07-28 18:06:48 +02:00
2021-07-22 18:23:48 +02:00
#define DS_OSX ((DisplayServerOSX *)(DisplayServerOSX::get_singleton()))
/*************************************************************************/
/* GodotApplication */
/*************************************************************************/
@interface GodotApplication : NSApplication
@end
@implementation GodotApplication
- (void)sendEvent:(NSEvent *)event {
if (DS_OSX) {
DS_OSX->_send_event(event);
}
// From http://cocoadev.com/index.pl?GameKeyboardHandlingAlmost
// This works around an AppKit bug, where key up events while holding
// down the command key don't get sent to the key window.
if ([event type] == NSEventTypeKeyUp && ([event modifierFlags] & NSEventModifierFlagCommand)) {
[[self keyWindow] sendEvent:event];
} else {
[super sendEvent:event];
}
}
@end
/*************************************************************************/
/* GodotApplicationDelegate */
/*************************************************************************/
@interface GodotApplicationDelegate : NSObject
- (void)forceUnbundledWindowActivationHackStep1;
- (void)forceUnbundledWindowActivationHackStep2;
- (void)forceUnbundledWindowActivationHackStep3;
@end
@implementation GodotApplicationDelegate
- (void)forceUnbundledWindowActivationHackStep1 {
2022-01-11 19:43:29 +01:00
// Step 1: Switch focus to macOS SystemUIServer process.
2021-07-22 18:23:48 +02:00
// Required to perform step 2, TransformProcessType will fail if app is already the in focus.
2022-01-11 19:43:29 +01:00
for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.systemuiserver"]) {
2021-07-22 18:23:48 +02:00
[app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
break;
}
[self performSelector:@selector(forceUnbundledWindowActivationHackStep2)
withObject:nil
afterDelay:0.02];
}
- (void)forceUnbundledWindowActivationHackStep2 {
// Step 2: Register app as foreground process.
ProcessSerialNumber psn = { 0, kCurrentProcess };
(void)TransformProcessType(&psn, kProcessTransformToForegroundApplication);
[self performSelector:@selector(forceUnbundledWindowActivationHackStep3) withObject:nil afterDelay:0.02];
}
- (void)forceUnbundledWindowActivationHackStep3 {
// Step 3: Switch focus back to app window.
[[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateIgnoringOtherApps];
}
- (void)applicationDidFinishLaunching:(NSNotification *)notice {
NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
2022-01-11 19:43:29 +01:00
if (nsappname == nil || isatty(STDOUT_FILENO) || isatty(STDIN_FILENO) || isatty(STDERR_FILENO)) {
// If the executable is started from terminal or is not bundled, macOS WindowServer won't register and activate app window correctly (menu and title bar are grayed out and input ignored).
2021-07-22 18:23:48 +02:00
[self performSelector:@selector(forceUnbundledWindowActivationHackStep1) withObject:nil afterDelay:0.02];
}
}
- (void)applicationDidResignActive:(NSNotification *)notification {
if (OS::get_singleton()->get_main_loop()) {
OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT);
}
}
- (void)applicationDidBecomeActive:(NSNotification *)notification {
if (OS::get_singleton()->get_main_loop()) {
OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN);
}
}
- (void)globalMenuCallback:(id)sender {
if (DS_OSX) {
return DS_OSX->_menu_callback(sender);
}
}
- (NSMenu *)applicationDockMenu:(NSApplication *)sender {
if (DS_OSX) {
return DS_OSX->_get_dock_menu();
} else {
return nullptr;
}
}
- (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename {
// Note: may be called called before main loop init!
char *utfs = strdup([filename UTF8String]);
((OS_OSX *)OS_OSX::get_singleton())->open_with_filename.parse_utf8(utfs);
free(utfs);
#ifdef TOOLS_ENABLED
// Open new instance
if (OS_OSX::get_singleton()->get_main_loop()) {
List<String> args;
args.push_back(((OS_OSX *)OS_OSX::get_singleton())->open_with_filename);
String exec = OS_OSX::get_singleton()->get_executable_path();
OS_OSX::get_singleton()->create_process(exec, args);
}
#endif
return YES;
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
if (DS_OSX) {
DS_OSX->_send_window_event(DS_OSX->windows[DisplayServerOSX::MAIN_WINDOW_ID], DisplayServerOSX::WINDOW_EVENT_CLOSE_REQUEST);
}
return NSTerminateCancel;
}
- (void)showAbout:(id)sender {
if (OS_OSX::get_singleton()->get_main_loop()) {
OS_OSX::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_ABOUT);
}
}
@end
2020-03-07 17:02:54 +01:00
/*************************************************************************/
/* OSXTerminalLogger */
/*************************************************************************/
2017-07-28 18:06:48 +02:00
2020-03-07 17:02:54 +01:00
class OSXTerminalLogger : public StdLogger {
public:
2021-11-26 10:18:15 +01:00
virtual void log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify = false, ErrorType p_type = ERR_ERROR) {
2020-03-07 17:02:54 +01:00
if (!should_log(true)) {
return;
2017-07-28 18:06:48 +02:00
}
2020-03-07 17:02:54 +01:00
const char *err_details;
if (p_rationale && p_rationale[0])
err_details = p_rationale;
else
err_details = p_code;
2019-06-22 18:34:26 +02:00
2020-03-07 17:02:54 +01:00
switch (p_type) {
case ERR_WARNING:
2020-04-26 20:17:10 +02:00
os_log_info(OS_LOG_DEFAULT,
"WARNING: %{public}s\nat: %{public}s (%{public}s:%i)",
err_details, p_function, p_file, p_line);
2020-03-07 17:02:54 +01:00
logf_error("\E[1;33mWARNING:\E[0;93m %s\n", err_details);
logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
break;
case ERR_SCRIPT:
2020-04-26 20:17:10 +02:00
os_log_error(OS_LOG_DEFAULT,
"SCRIPT ERROR: %{public}s\nat: %{public}s (%{public}s:%i)",
err_details, p_function, p_file, p_line);
2020-03-07 17:02:54 +01:00
logf_error("\E[1;35mSCRIPT ERROR:\E[0;95m %s\n", err_details);
logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
break;
case ERR_SHADER:
2020-04-26 20:17:10 +02:00
os_log_error(OS_LOG_DEFAULT,
"SHADER ERROR: %{public}s\nat: %{public}s (%{public}s:%i)",
err_details, p_function, p_file, p_line);
2020-03-07 17:02:54 +01:00
logf_error("\E[1;36mSHADER ERROR:\E[0;96m %s\n", err_details);
logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
break;
case ERR_ERROR:
default:
2020-04-26 20:17:10 +02:00
os_log_error(OS_LOG_DEFAULT,
"ERROR: %{public}s\nat: %{public}s (%{public}s:%i)",
err_details, p_function, p_file, p_line);
2020-03-07 17:02:54 +01:00
logf_error("\E[1;31mERROR:\E[0;91m %s\n", err_details);
logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
break;
2019-01-22 17:17:39 +01:00
}
2017-07-26 15:29:48 +02:00
}
2015-04-02 06:32:02 +02:00
};
2020-03-07 17:02:54 +01:00
/*************************************************************************/
/* OS_OSX */
/*************************************************************************/
2017-08-07 13:09:56 +02:00
2018-01-20 16:17:39 +01:00
String OS_OSX::get_unique_id() const {
2020-03-07 17:02:54 +01:00
static String serial_number;
2018-01-20 16:17:39 +01:00
2020-12-15 13:04:21 +01:00
if (serial_number.is_empty()) {
2020-03-07 17:02:54 +01:00
io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"));
2021-04-29 11:47:24 +02:00
CFStringRef serialNumberAsCFString = nullptr;
2020-03-07 17:02:54 +01:00
if (platformExpert) {
serialNumberAsCFString = (CFStringRef)IORegistryEntryCreateCFProperty(platformExpert, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0);
IOObjectRelease(platformExpert);
}
2015-04-02 06:32:02 +02:00
2020-03-07 17:02:54 +01:00
NSString *serialNumberAsNSString = nil;
if (serialNumberAsCFString) {
2022-01-25 09:07:01 +01:00
serialNumberAsNSString = [NSString stringWithString:(__bridge NSString *)serialNumberAsCFString];
2020-03-07 17:02:54 +01:00
CFRelease(serialNumberAsCFString);
}
2015-04-02 06:32:02 +02:00
2020-03-07 17:02:54 +01:00
serial_number = [serialNumberAsNSString UTF8String];
}
2014-02-10 02:10:30 +01:00
2020-03-07 17:02:54 +01:00
return serial_number;
2014-02-10 02:10:30 +01:00
}
2021-07-22 18:23:48 +02:00
void OS_OSX::alert(const String &p_alert, const String &p_title) {
NSAlert *window = [[NSAlert alloc] init];
NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
NSString *ns_alert = [NSString stringWithUTF8String:p_alert.utf8().get_data()];
[window addButtonWithTitle:@"OK"];
[window setMessageText:ns_title];
[window setInformativeText:ns_alert];
[window setAlertStyle:NSAlertStyleWarning];
id key_window = [[NSApplication sharedApplication] keyWindow];
[window runModal];
if (key_window) {
[key_window makeKeyAndOrderFront:nil];
}
}
2020-03-07 17:02:54 +01:00
void OS_OSX::initialize_core() {
OS_Unix::initialize_core();
2018-01-30 20:39:53 +01:00
2020-03-07 17:02:54 +01:00
DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_RESOURCES);
DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_USERDATA);
DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_FILESYSTEM);
2018-01-30 20:39:53 +01:00
}
2020-03-07 17:02:54 +01:00
void OS_OSX::initialize_joypads() {
2020-04-28 15:19:37 +02:00
joypad_osx = memnew(JoypadOSX(Input::get_singleton()));
2018-01-30 20:39:53 +01:00
}
2020-03-07 17:02:54 +01:00
void OS_OSX::initialize() {
crash_handler.initialize();
initialize_core();
//ensure_user_data_dir();
2019-11-28 13:41:07 +01:00
}
2020-03-07 17:02:54 +01:00
void OS_OSX::finalize() {
#ifdef COREMIDI_ENABLED
midi_driver.close();
#endif
2016-07-21 17:30:20 +02:00
2020-03-07 17:02:54 +01:00
delete_main_loop();
2017-12-10 19:38:26 +01:00
2020-08-02 20:30:56 +02:00
if (joypad_osx) {
memdelete(joypad_osx);
}
2017-12-10 19:38:26 +01:00
}
2020-03-07 17:02:54 +01:00
void OS_OSX::set_main_loop(MainLoop *p_main_loop) {
main_loop = p_main_loop;
2017-12-10 19:38:26 +01:00
}
2020-03-07 17:02:54 +01:00
void OS_OSX::delete_main_loop() {
if (!main_loop)
return;
memdelete(main_loop);
2021-04-29 11:47:24 +02:00
main_loop = nullptr;
2020-03-07 17:02:54 +01:00
}
2017-12-10 19:38:26 +01:00
2020-03-07 17:02:54 +01:00
String OS_OSX::get_name() const {
return "macOS";
}
2017-06-27 18:13:03 +02:00
2021-08-27 23:19:51 +02:00
_FORCE_INLINE_ String _get_framework_executable(const String p_path) {
// Append framework executable name, or return as is if p_path is not a framework.
DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
if (da->dir_exists(p_path) && da->file_exists(p_path.plus_file(p_path.get_file().get_basename()))) {
return p_path.plus_file(p_path.get_file().get_basename());
} else {
return p_path;
}
}
2020-03-07 17:02:54 +01:00
Error OS_OSX::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
2021-08-27 23:19:51 +02:00
String path = _get_framework_executable(p_path);
2017-06-27 18:13:03 +02:00
2020-03-07 17:02:54 +01:00
if (!FileAccess::exists(path)) {
2021-08-27 23:19:51 +02:00
// This code exists so gdnative can load .dylib files from within the executable path.
path = _get_framework_executable(get_executable_path().get_base_dir().plus_file(p_path.get_file()));
2017-06-27 18:13:03 +02:00
}
2017-07-03 03:44:42 +02:00
2020-03-07 17:02:54 +01:00
if (!FileAccess::exists(path)) {
2021-08-27 23:19:51 +02:00
// This code exists so gdnative can load .dylib files from a standard macOS location.
path = _get_framework_executable(get_executable_path().get_base_dir().plus_file("../Frameworks").plus_file(p_path.get_file()));
2020-03-07 17:02:54 +01:00
}
2017-07-03 03:44:42 +02:00
2020-03-07 17:02:54 +01:00
p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ", error: " + dlerror() + ".");
return OK;
2017-06-27 18:13:03 +02:00
}
2020-03-07 17:02:54 +01:00
MainLoop *OS_OSX::get_main_loop() const {
return main_loop;
2017-06-27 18:13:03 +02:00
}
2020-03-07 17:02:54 +01:00
String OS_OSX::get_config_path() const {
2021-05-21 12:48:12 +02:00
// The XDG Base Directory specification technically only applies on Linux/*BSD, but it doesn't hurt to support it on macOS as well.
2020-03-07 17:02:54 +01:00
if (has_environment("XDG_CONFIG_HOME")) {
2021-06-03 15:41:22 +02:00
if (get_environment("XDG_CONFIG_HOME").is_absolute_path()) {
2021-05-07 19:02:35 +02:00
return get_environment("XDG_CONFIG_HOME");
} else {
WARN_PRINT_ONCE("`XDG_CONFIG_HOME` is a relative path. Ignoring its value and falling back to `$HOME/Library/Application Support` or `.` per the XDG Base Directory specification.");
}
2021-05-21 12:48:12 +02:00
}
if (has_environment("HOME")) {
2020-03-07 17:02:54 +01:00
return get_environment("HOME").plus_file("Library/Application Support");
2014-02-10 02:10:30 +01:00
}
2021-05-21 12:48:12 +02:00
return ".";
2014-02-10 02:10:30 +01:00
}
2020-03-07 17:02:54 +01:00
String OS_OSX::get_data_path() const {
2021-05-21 12:48:12 +02:00
// The XDG Base Directory specification technically only applies on Linux/*BSD, but it doesn't hurt to support it on macOS as well.
2020-03-07 17:02:54 +01:00
if (has_environment("XDG_DATA_HOME")) {
2021-06-03 15:41:22 +02:00
if (get_environment("XDG_DATA_HOME").is_absolute_path()) {
2021-05-07 19:02:35 +02:00
return get_environment("XDG_DATA_HOME");
} else {
WARN_PRINT_ONCE("`XDG_DATA_HOME` is a relative path. Ignoring its value and falling back to `get_config_path()` per the XDG Base Directory specification.");
}
2015-01-08 08:26:27 +01:00
}
2021-05-21 12:48:12 +02:00
return get_config_path();
2015-01-08 08:26:27 +01:00
}
2017-04-09 13:22:40 +02:00
2020-03-07 17:02:54 +01:00
String OS_OSX::get_cache_path() const {
2021-05-21 12:48:12 +02:00
// The XDG Base Directory specification technically only applies on Linux/*BSD, but it doesn't hurt to support it on macOS as well.
2020-03-07 17:02:54 +01:00
if (has_environment("XDG_CACHE_HOME")) {
2021-06-03 15:41:22 +02:00
if (get_environment("XDG_CACHE_HOME").is_absolute_path()) {
2021-05-07 19:02:35 +02:00
return get_environment("XDG_CACHE_HOME");
} else {
Fix various typos with codespell
Found via `codespell -q 3 -S ./thirdparty,*.po,./DONORS.md -L ackward,ang,ans,ba,beng,cas,childs,childrens,dof,doubleclick,fave,findn,hist,inout,leapyear,lod,nd,numer,ois,ony,paket,seeked,sinc,switchs,te,uint`
2021-07-07 17:17:32 +02:00
WARN_PRINT_ONCE("`XDG_CACHE_HOME` is a relative path. Ignoring its value and falling back to `$HOME/Library/Caches` or `get_config_path()` per the XDG Base Directory specification.");
2021-05-07 19:02:35 +02:00
}
2021-05-21 12:48:12 +02:00
}
if (has_environment("HOME")) {
2020-03-07 17:02:54 +01:00
return get_environment("HOME").plus_file("Library/Caches");
2015-01-08 08:26:27 +01:00
}
2021-05-21 12:48:12 +02:00
return get_config_path();
2015-01-08 08:26:27 +01:00
}
2014-02-10 02:10:30 +01:00
2020-03-07 17:02:54 +01:00
String OS_OSX::get_bundle_resource_dir() const {
2021-05-13 08:25:09 +02:00
String ret;
2020-03-07 17:02:54 +01:00
NSBundle *main = [NSBundle mainBundle];
2021-05-13 08:25:09 +02:00
if (main) {
NSString *resourcePath = [main resourcePath];
ret.parse_utf8([resourcePath UTF8String]);
}
return ret;
}
2014-02-10 02:10:30 +01:00
2021-05-13 08:25:09 +02:00
String OS_OSX::get_bundle_icon_path() const {
2020-03-07 17:02:54 +01:00
String ret;
2019-03-03 23:52:18 +01:00
2021-05-13 08:25:09 +02:00
NSBundle *main = [NSBundle mainBundle];
if (main) {
NSString *iconPath = [[main infoDictionary] objectForKey:@"CFBundleIconFile"];
if (iconPath) {
ret.parse_utf8([iconPath UTF8String]);
}
}
2020-03-07 17:02:54 +01:00
return ret;
2014-02-10 02:10:30 +01:00
}
2020-03-07 17:02:54 +01:00
// Get properly capitalized engine name for system paths
String OS_OSX::get_godot_dir_name() const {
return String(VERSION_SHORT_NAME).capitalize();
}
2018-01-10 12:22:28 +01:00
2021-07-11 03:39:31 +02:00
String OS_OSX::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
2020-03-07 17:02:54 +01:00
NSSearchPathDirectory id;
bool found = true;
2018-01-10 12:22:28 +01:00
2020-03-07 17:02:54 +01:00
switch (p_dir) {
case SYSTEM_DIR_DESKTOP: {
id = NSDesktopDirectory;
} break;
case SYSTEM_DIR_DOCUMENTS: {
id = NSDocumentDirectory;
} break;
case SYSTEM_DIR_DOWNLOADS: {
id = NSDownloadsDirectory;
} break;
case SYSTEM_DIR_MOVIES: {
id = NSMoviesDirectory;
} break;
case SYSTEM_DIR_MUSIC: {
id = NSMusicDirectory;
} break;
case SYSTEM_DIR_PICTURES: {
id = NSPicturesDirectory;
} break;
default: {
found = false;
}
}
2018-01-10 12:22:28 +01:00
2020-03-07 17:02:54 +01:00
String ret;
if (found) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(id, NSUserDomainMask, YES);
if (paths && [paths count] >= 1) {
char *utfs = strdup([[paths firstObject] UTF8String]);
ret.parse_utf8(utfs);
free(utfs);
2018-01-10 12:22:28 +01:00
}
}
2020-03-07 17:02:54 +01:00
return ret;
2018-01-10 12:22:28 +01:00
}
2020-03-07 17:02:54 +01:00
Error OS_OSX::shell_open(String p_uri) {
2020-07-04 06:00:48 +02:00
NSString *string = [NSString stringWithUTF8String:p_uri.utf8().get_data()];
NSURL *uri = [[NSURL alloc] initWithString:string];
// Escape special characters in filenames
if (!uri || !uri.scheme || [uri.scheme isEqual:@"file"]) {
uri = [[NSURL alloc] initWithString:[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
}
[[NSWorkspace sharedWorkspace] openURL:uri];
2020-03-07 17:02:54 +01:00
return OK;
}
2017-05-22 11:17:14 +02:00
2020-03-07 17:02:54 +01:00
String OS_OSX::get_locale() const {
NSString *locale_code = [[NSLocale preferredLanguages] objectAtIndex:0];
2020-07-25 22:42:11 +02:00
return String([locale_code UTF8String]).replace("-", "_");
2014-02-10 02:10:30 +01:00
}
2020-03-07 17:02:54 +01:00
String OS_OSX::get_executable_path() const {
int ret;
pid_t pid;
char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
pid = getpid();
ret = proc_pidpath(pid, pathbuf, sizeof(pathbuf));
if (ret <= 0) {
return OS::get_executable_path();
} else {
String path;
path.parse_utf8(pathbuf);
2017-12-14 12:59:46 +01:00
2020-03-07 17:02:54 +01:00
return path;
}
2017-12-14 12:59:46 +01:00
}
2021-11-01 10:12:52 +01:00
Error OS_OSX::create_instance(const List<String> &p_arguments, ProcessID *r_child_id) {
// If executable is bundled, always execute editor instances as an app bundle to ensure app window is registered and activated correctly.
NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
if (nsappname != nil) {
String path;
path.parse_utf8([[[NSBundle mainBundle] bundlePath] UTF8String]);
2021-12-16 14:00:55 +01:00
return create_process(path, p_arguments, r_child_id, false);
2021-11-01 10:12:52 +01:00
} else {
2021-12-16 14:00:55 +01:00
return create_process(get_executable_path(), p_arguments, r_child_id, false);
2021-11-01 10:12:52 +01:00
}
}
2021-12-16 14:00:55 +01:00
Error OS_OSX::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
2021-11-01 10:12:52 +01:00
if (@available(macOS 10.15, *)) {
// Use NSWorkspace if path is an .app bundle.
NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
NSBundle *bundle = [NSBundle bundleWithURL:url];
if (bundle) {
NSMutableArray *arguments = [[NSMutableArray alloc] init];
for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
[arguments addObject:[NSString stringWithUTF8String:E->get().utf8().get_data()]];
}
NSWorkspaceOpenConfiguration *configuration = [[NSWorkspaceOpenConfiguration alloc] init];
[configuration setArguments:arguments];
[configuration setCreatesNewApplicationInstance:YES];
__block dispatch_semaphore_t lock = dispatch_semaphore_create(0);
__block Error err = ERR_TIMEOUT;
__block pid_t pid = 0;
[[NSWorkspace sharedWorkspace] openApplicationAtURL:url
configuration:configuration
completionHandler:^(NSRunningApplication *app, NSError *error) {
if (error) {
err = ERR_CANT_FORK;
NSLog(@"Failed to execute: %@", error.localizedDescription);
} else {
pid = [app processIdentifier];
err = OK;
}
dispatch_semaphore_signal(lock);
}];
dispatch_semaphore_wait(lock, dispatch_time(DISPATCH_TIME_NOW, 20000000000)); // 20 sec timeout, wait for app to launch.
if (err == OK) {
if (r_child_id) {
*r_child_id = (ProcessID)pid;
}
}
return err;
} else {
2021-12-16 14:00:55 +01:00
return OS_Unix::create_process(p_path, p_arguments, r_child_id, p_open_console);
2021-11-01 10:12:52 +01:00
}
} else {
2021-12-16 14:00:55 +01:00
return OS_Unix::create_process(p_path, p_arguments, r_child_id, p_open_console);
2021-11-01 10:12:52 +01:00
}
}
2021-11-08 11:35:13 +01:00
void OS_OSX::pre_wait_observer_cb(CFRunLoopObserverRef p_observer, CFRunLoopActivity p_activiy, void *p_context) {
// Prevent main loop from sleeping and redraw window during resize / modal popups.
if (get_singleton()->get_main_loop()) {
Main::force_redraw();
if (!Main::is_iterating()) { // Avoid cyclic loop.
Main::iteration();
}
}
CFRunLoopWakeUp(CFRunLoopGetCurrent()); // Prevent main loop from sleeping.
}
2014-02-10 02:10:30 +01:00
void OS_OSX::run() {
force_quit = false;
2021-11-08 11:35:13 +01:00
if (!main_loop) {
2014-02-10 02:10:30 +01:00
return;
2021-11-08 11:35:13 +01:00
}
2014-02-10 02:10:30 +01:00
2020-12-22 10:50:29 +01:00
main_loop->initialize();
2014-02-10 02:10:30 +01:00
2021-11-08 11:35:13 +01:00
CFRunLoopObserverRef pre_wait_observer = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, true, 0, &pre_wait_observer_cb, nullptr);
CFRunLoopAddObserver(CFRunLoopGetCurrent(), pre_wait_observer, kCFRunLoopCommonModes);
2018-01-15 09:20:45 +01:00
bool quit = false;
while (!force_quit && !quit) {
@try {
2020-03-07 17:02:54 +01:00
if (DisplayServer::get_singleton()) {
DisplayServer::get_singleton()->process_events(); // get rid of pending events
}
2018-01-15 09:20:45 +01:00
joypad_osx->process_joypads();
2020-07-13 20:13:38 +02:00
if (Main::iteration()) {
2018-01-15 09:20:45 +01:00
quit = true;
}
} @catch (NSException *exception) {
2022-01-06 10:34:10 +01:00
ERR_PRINT("NSException: " + String::utf8([exception reason].UTF8String));
2018-01-15 09:20:45 +01:00
}
2014-02-10 02:10:30 +01:00
};
2021-11-08 11:35:13 +01:00
CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), pre_wait_observer, kCFRunLoopCommonModes);
CFRelease(pre_wait_observer);
2020-12-22 10:50:29 +01:00
main_loop->finalize();
2014-02-10 02:10:30 +01:00
}
2017-09-25 15:15:11 +02:00
Error OS_OSX::move_to_trash(const String &p_path) {
NSFileManager *fm = [NSFileManager defaultManager];
NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
NSError *err;
if (![fm trashItemAtURL:url resultingItemURL:nil error:&err]) {
2022-01-06 10:34:10 +01:00
ERR_PRINT("trashItemAtURL error: " + String::utf8(err.localizedDescription.UTF8String));
2017-09-25 15:15:11 +02:00
return FAILED;
}
return OK;
}
2014-02-10 02:10:30 +01:00
OS_OSX::OS_OSX() {
2021-04-29 11:47:24 +02:00
main_loop = nullptr;
2020-03-07 17:02:54 +01:00
force_quit = false;
2017-09-22 07:56:02 +02:00
2017-11-21 10:35:01 +01:00
Vector<Logger *> loggers;
loggers.push_back(memnew(OSXTerminalLogger));
_set_logger(memnew(CompositeLogger(loggers)));
2018-01-12 15:38:19 +01:00
2018-10-25 15:59:26 +02:00
#ifdef COREAUDIO_ENABLED
2018-03-04 18:18:05 +01:00
AudioDriverManager::add_driver(&audio_driver);
2018-10-25 15:59:26 +02:00
#endif
2020-03-07 17:02:54 +01:00
DisplayServerOSX::register_osx_driver();
2021-07-22 18:23:48 +02:00
// Implicitly create shared NSApplication instance
[GodotApplication sharedApplication];
// In case we are unbundled, make us a proper UI application
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
// Menu bar setup must go between sharedApplication above and
// finishLaunching below, in order to properly emulate the behavior
// of NSApplicationMain
2022-01-25 09:07:01 +01:00
NSMenu *main_menu = [[NSMenu alloc] initWithTitle:@""];
2021-07-22 18:23:48 +02:00
[NSApp setMainMenu:main_menu];
[NSApp finishLaunching];
id delegate = [[GodotApplicationDelegate alloc] init];
ERR_FAIL_COND(!delegate);
[NSApp setDelegate:delegate];
//process application:openFile: event
while (true) {
NSEvent *event = [NSApp
nextEventMatchingMask:NSEventMaskAny
untilDate:[NSDate distantPast]
inMode:NSDefaultRunLoopMode
dequeue:YES];
if (event == nil) {
break;
}
[NSApp sendEvent:event];
}
[NSApp activateIgnoringOtherApps:YES];
2014-02-10 02:10:30 +01:00
}
2017-07-19 22:00:46 +02:00
bool OS_OSX::_check_internal_feature_support(const String &p_feature) {
2019-02-26 15:58:47 +01:00
return p_feature == "pc";
2017-07-19 22:00:46 +02:00
}
2017-09-08 03:01:49 +02:00
void OS_OSX::disable_crash_handler() {
crash_handler.disable();
}
bool OS_OSX::is_disable_crash_handler() const {
return crash_handler.is_disabled();
}