Skip to content
0.2.0-dev Download ZIP
924 lines ·31.9 KB Raw
1/**************************************************************************/
2/* os_apple_embedded.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
31#import "os_apple_embedded.h"
32
33#ifdef APPLE_EMBEDDED_ENABLED
34
35#include "core/config/engine.h"
36#include "core/config/project_settings.h"
37#include "core/io/dir_access.h"
38#include "core/io/file_access.h"
39#include "core/os/main_loop.h"
40#include "core/os/os.h"
41#include "core/profiling/profiling.h"
42#import "drivers/apple/os_log_logger.h"
43#import "drivers/apple_embedded/display_server_apple_embedded.h"
44#import "drivers/apple_embedded/godot_app_delegate_service_apple_embedded.h"
45#import "drivers/apple_embedded/godot_view_apple_embedded.h"
46#import "drivers/apple_embedded/godot_view_controller.h"
47#ifdef SDL_ENABLED
48#include "drivers/sdl/joypad_sdl.h"
49#endif
50#include "main/main.h"
51#include "servers/audio/audio_driver.h"
52#include "servers/camera/camera_server.h"
53#include "servers/display/accessibility_server.h"
54
55#import <AVFoundation/AVFAudio.h>
56#import <AudioToolbox/AudioServices.h>
57#import <CoreText/CoreText.h>
58#import <UIKit/UIKit.h>
59#import <dlfcn.h>
60#include <sys/sysctl.h>
61
62#include <iterator>
63
64#if defined(RD_ENABLED)
65#include "servers/rendering/renderer_rd/renderer_compositor_rd.h"
66
67#import <QuartzCore/CAMetalLayer.h>
68
69#if defined(VULKAN_ENABLED)
70#include <drivers/vulkan/godot_vulkan.h>
71#endif // VULKAN_ENABLED
72#endif
73
74// Initialization order between compilation units is not guaranteed,
75// so we use this as a hack to ensure certain code is called before
76// everything else, but after all units are initialized.
77typedef void (*init_callback)();
78static init_callback *apple_init_callbacks = nullptr;
79static int apple_embedded_platform_init_callbacks_count = 0;
80static int apple_embedded_platform_init_callbacks_capacity = 0;
81HashMap<String, void *> OS_AppleEmbedded::dynamic_symbol_lookup_table;
82
83void add_apple_embedded_platform_init_callback(init_callback cb) {
84 if (apple_embedded_platform_init_callbacks_count == apple_embedded_platform_init_callbacks_capacity) {
85 void *new_ptr = realloc(apple_init_callbacks, sizeof(cb) * (apple_embedded_platform_init_callbacks_capacity + 32));
86 if (new_ptr) {
87 apple_init_callbacks = (init_callback *)(new_ptr);
88 apple_embedded_platform_init_callbacks_capacity += 32;
89 } else {
90 ERR_FAIL_MSG("Unable to allocate memory for extension callbacks.");
91 }
92 }
93 apple_init_callbacks[apple_embedded_platform_init_callbacks_count++] = cb;
94}
95
96void register_dynamic_symbol(char *name, void *address) {
97 OS_AppleEmbedded::dynamic_symbol_lookup_table[String(name)] = address;
98}
99
100Rect2 fit_keep_aspect_centered(const Vector2 &p_container, const Vector2 &p_rect) {
101 real_t available_ratio = p_container.width / p_container.height;
102 real_t fit_ratio = p_rect.width / p_rect.height;
103 Rect2 result;
104 if (fit_ratio < available_ratio) {
105 // Fit height - we'll have horizontal gaps
106 result.size.height = p_container.height;
107 result.size.width = p_container.height * fit_ratio;
108 result.position.y = 0;
109 result.position.x = (p_container.width - result.size.width) * 0.5f;
110 } else {
111 // Fit width - we'll have vertical gaps
112 result.size.width = p_container.width;
113 result.size.height = p_container.width / fit_ratio;
114 result.position.x = 0;
115 result.position.y = (p_container.height - result.size.height) * 0.5f;
116 }
117 return result;
118}
119
120Rect2 fit_keep_aspect_covered(const Vector2 &p_container, const Vector2 &p_rect) {
121 real_t available_ratio = p_container.width / p_container.height;
122 real_t fit_ratio = p_rect.width / p_rect.height;
123 Rect2 result;
124 if (fit_ratio < available_ratio) {
125 // Need to scale up to fit width, and crop height
126 result.size.width = p_container.width;
127 result.size.height = p_container.width / fit_ratio;
128 result.position.x = 0;
129 result.position.y = (p_container.height - result.size.height) * 0.5f;
130 } else {
131 // Need to scale up to fit height, and crop width
132 result.size.width = p_container.height * fit_ratio;
133 result.size.height = p_container.height;
134 result.position.x = (p_container.width - result.size.width) * 0.5f;
135 result.position.y = 0;
136 }
137 return result;
138}
139
140OS_AppleEmbedded *OS_AppleEmbedded::get_singleton() {
141 return (OS_AppleEmbedded *)OS::get_singleton();
142}
143
144OS_AppleEmbedded::OS_AppleEmbedded() {
145 for (int i = 0; i < apple_embedded_platform_init_callbacks_count; ++i) {
146 apple_init_callbacks[i]();
147 }
148 free(apple_init_callbacks);
149 apple_init_callbacks = nullptr;
150 apple_embedded_platform_init_callbacks_count = 0;
151 apple_embedded_platform_init_callbacks_capacity = 0;
152
153 main_loop = nullptr;
154
155 Vector<Logger *> loggers;
156 loggers.push_back(memnew(OsLogLogger(NSBundle.mainBundle.bundleIdentifier.UTF8String)));
157 _set_logger(memnew(CompositeLogger(loggers)));
158
159 AudioDriverManager::add_driver(&audio_driver);
160}
161
162OS_AppleEmbedded::~OS_AppleEmbedded() {}
163
164Error OS_AppleEmbedded::get_entropy(uint8_t *r_buffer, int p_bytes) {
165 int status = SecRandomCopyBytes(kSecRandomDefault, p_bytes, r_buffer);
166 return status == errSecSuccess ? OK : FAILED;
167}
168
169void OS_AppleEmbedded::alert(const String &p_alert, const String &p_title) {
170 const CharString utf8_alert = p_alert.utf8();
171 const CharString utf8_title = p_title.utf8();
172 AppleEmbedded::alert(utf8_alert.get_data(), utf8_title.get_data());
173}
174
175void OS_AppleEmbedded::initialize_core() {
176 OS_Unix::initialize_core();
177}
178
179void OS_AppleEmbedded::initialize() {
180 initialize_core();
181}
182
183void OS_AppleEmbedded::initialize_joypads() {
184#ifdef SDL_ENABLED
185 joypad_sdl = memnew(JoypadSDL());
186 if (joypad_sdl->initialize() != OK) {
187 ERR_PRINT("Couldn't initialize SDL joypad input driver.");
188 memdelete(joypad_sdl);
189 joypad_sdl = nullptr;
190 }
191#endif
192}
193
194void OS_AppleEmbedded::initialize_modules() {
195 apple_embedded = memnew(AppleEmbedded);
196 Engine::get_singleton()->add_singleton(Engine::Singleton("AppleEmbedded", apple_embedded));
197}
198
199void OS_AppleEmbedded::deinitialize_modules() {
200#ifdef SDL_ENABLED
201 memdelete(joypad_sdl);
202#endif
203 memdelete(apple_embedded);
204}
205
206void OS_AppleEmbedded::set_main_loop(MainLoop *p_main_loop) {
207 main_loop = p_main_loop;
208}
209
210MainLoop *OS_AppleEmbedded::get_main_loop() const {
211 return main_loop;
212}
213
214void OS_AppleEmbedded::delete_main_loop() {
215 if (main_loop) {
216 main_loop->finalize();
217 memdelete(main_loop);
218 }
219
220 main_loop = nullptr;
221}
222
223bool OS_AppleEmbedded::iterate() {
224 if (!main_loop) {
225 return true;
226 }
227
228 GodotProfileFrameMark;
229 GodotProfileZone("OS_AppleEmbedded::iterate");
230
231 if (DisplayServer::get_singleton()) {
232 DisplayServer::get_singleton()->process_events();
233 }
234
235#ifdef SDL_ENABLED
236 if (joypad_sdl) {
237 joypad_sdl->process_events();
238 }
239#endif
240
241 return Main::iteration();
242}
243
244void OS_AppleEmbedded::start() {
245 if (Main::start() == EXIT_SUCCESS) {
246 main_loop->initialize();
247 }
248}
249
250void OS_AppleEmbedded::finalize() {
251 deinitialize_modules();
252
253 // Already gets called
254 //delete_main_loop();
255}
256
257// MARK: Dynamic Libraries
258
259_FORCE_INLINE_ String OS_AppleEmbedded::get_framework_executable(const String &p_path) {
260 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
261
262 // Read framework bundle to get executable name.
263 NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
264 NSBundle *bundle = [NSBundle bundleWithURL:url];
265 if (bundle) {
266 String exe_path = String::utf8([[bundle executablePath] UTF8String]);
267 if (da->file_exists(exe_path)) {
268 return exe_path;
269 }
270 }
271
272 // Try default executable name (invalid framework).
273 if (da->dir_exists(p_path) && da->file_exists(p_path.path_join(p_path.get_file().get_basename()))) {
274 return p_path.path_join(p_path.get_file().get_basename());
275 }
276
277 // Not a framework, try loading as .dylib.
278 return p_path;
279}
280
281Error OS_AppleEmbedded::open_dynamic_library(const String &p_path, void *&p_library_handle, GDExtensionData *p_data) {
282 if (p_path.length() == 0) {
283 // Static xcframework.
284 p_library_handle = RTLD_SELF;
285
286 if (p_data != nullptr && p_data->r_resolved_path != nullptr) {
287 *p_data->r_resolved_path = p_path;
288 }
289
290 return OK;
291 }
292
293 String path = get_framework_executable(p_path);
294
295 if (!FileAccess::exists(path)) {
296 // Load .dylib or framework from within the executable path.
297 path = get_framework_executable(get_executable_path().get_base_dir().path_join(p_path.get_file()));
298 }
299
300 if (!FileAccess::exists(path)) {
301 // Load .dylib converted to framework from within the executable path.
302 path = get_framework_executable(get_executable_path().get_base_dir().path_join(p_path.get_file().get_basename() + ".framework"));
303 }
304
305 if (!FileAccess::exists(path)) {
306 // Load .dylib from within the executable path.
307 path = get_framework_executable(get_executable_path().get_base_dir().path_join(p_path.get_file().get_basename() + ".dylib"));
308 }
309
310 if (!FileAccess::exists(path)) {
311 // Load .dylib or framework from a standard iOS location.
312 path = get_framework_executable(get_executable_path().get_base_dir().path_join("Frameworks").path_join(p_path.get_file()));
313 }
314
315 if (!FileAccess::exists(path)) {
316 // Load .dylib converted to framework from a standard iOS location.
317 path = get_framework_executable(get_executable_path().get_base_dir().path_join("Frameworks").path_join(p_path.get_file().get_basename() + ".framework"));
318 }
319
320 if (!FileAccess::exists(path)) {
321 // Load .dylib from a standard iOS location.
322 path = get_framework_executable(get_executable_path().get_base_dir().path_join("Frameworks").path_join(p_path.get_file().get_basename() + ".dylib"));
323 }
324
325 if (!FileAccess::exists(path) && (p_path.ends_with(".a") || p_path.ends_with(".xcframework"))) {
326 // Static library already linked into the binary — use RTLD_SELF.
327 p_library_handle = RTLD_SELF;
328
329 if (p_data != nullptr && p_data->r_resolved_path != nullptr) {
330 *p_data->r_resolved_path = p_path;
331 }
332
333 return OK;
334 } else {
335 ERR_FAIL_COND_V(!FileAccess::exists(path), ERR_FILE_NOT_FOUND);
336 }
337 p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
338 ERR_FAIL_NULL_V_MSG(p_library_handle, ERR_CANT_OPEN, vformat("Can't open dynamic library: %s. Error: %s.", p_path, dlerror()));
339
340 if (p_data != nullptr && p_data->r_resolved_path != nullptr) {
341 *p_data->r_resolved_path = path;
342 }
343
344 return OK;
345}
346
347Error OS_AppleEmbedded::close_dynamic_library(void *p_library_handle) {
348 if (p_library_handle == RTLD_SELF) {
349 return OK;
350 }
351 return OS_Unix::close_dynamic_library(p_library_handle);
352}
353
354Error OS_AppleEmbedded::get_dynamic_library_symbol_handle(void *p_library_handle, const String &p_name, void *&p_symbol_handle, bool p_optional) {
355 if (p_library_handle == RTLD_SELF) {
356 void **ptr = OS_AppleEmbedded::dynamic_symbol_lookup_table.getptr(p_name);
357 if (ptr) {
358 p_symbol_handle = *ptr;
359 return OK;
360 }
361 }
362 return OS_Unix::get_dynamic_library_symbol_handle(p_library_handle, p_name, p_symbol_handle, p_optional);
363}
364
365String OS_AppleEmbedded::get_distribution_name() const {
366 return get_name();
367}
368
369String OS_AppleEmbedded::get_version() const {
370 NSOperatingSystemVersion ver = [NSProcessInfo processInfo].operatingSystemVersion;
371 return vformat("%d.%d.%d", (int64_t)ver.majorVersion, (int64_t)ver.minorVersion, (int64_t)ver.patchVersion);
372}
373
374String OS_AppleEmbedded::get_model_name() const {
375 String model = apple_embedded->get_model();
376 if (model != "") {
377 return model;
378 }
379
380 return OS_Unix::get_model_name();
381}
382
383Error OS_AppleEmbedded::shell_open(const String &p_uri) {
384 NSString *urlPath = [[NSString alloc] initWithUTF8String:p_uri.utf8().get_data()];
385 NSURL *url = [NSURL URLWithString:urlPath];
386
387 if (![[UIApplication sharedApplication] canOpenURL:url]) {
388 return ERR_CANT_OPEN;
389 }
390
391 print_verbose(vformat("Opening URL %s", p_uri));
392
393 [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
394
395 return OK;
396}
397
398String OS_AppleEmbedded::get_user_data_dir(const String &p_user_dir) const {
399 static String ret;
400 if (ret.is_empty()) {
401 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
402 if (paths && [paths count] >= 1) {
403 ret.append_utf8([[paths firstObject] UTF8String]);
404 }
405 }
406 return ret;
407}
408
409String OS_AppleEmbedded::get_cache_path() const {
410 static String ret;
411 if (ret.is_empty()) {
412 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
413 if (paths && [paths count] >= 1) {
414 ret.append_utf8([[paths firstObject] UTF8String]);
415 }
416 }
417 return ret;
418}
419
420String OS_AppleEmbedded::get_temp_path() const {
421 static String ret;
422 if (ret.is_empty()) {
423 NSURL *url = [NSURL fileURLWithPath:NSTemporaryDirectory()
424 isDirectory:YES];
425 if (url) {
426 ret = String::utf8([url.path UTF8String]);
427 ret = ret.trim_prefix("file://");
428 }
429 }
430 return ret;
431}
432
433String OS_AppleEmbedded::get_resource_dir() const {
434#ifdef TOOLS_ENABLED
435 return OS_Unix::get_resource_dir();
436#else
437 if (remote_fs_dir.is_empty()) {
438 return OS_Unix::get_resource_dir();
439 } else {
440 return remote_fs_dir;
441 }
442#endif
443}
444
445String OS_AppleEmbedded::get_bundle_resource_dir() const {
446 NSString *str = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"godot_path"];
447 if (!str) {
448 return OS_Unix::get_bundle_resource_dir();
449 } else {
450 String res_path = String::utf8([str cStringUsingEncoding:NSUTF8StringEncoding]);
451 if (res_path.is_relative_path()) {
452 res_path = String::utf8([[[NSBundle mainBundle] bundlePath] cStringUsingEncoding:NSUTF8StringEncoding]).path_join(res_path);
453 }
454 return res_path;
455 }
456}
457
458String OS_AppleEmbedded::get_locale() const {
459 NSString *preferredLanguage = [NSLocale preferredLanguages].firstObject;
460
461 if (preferredLanguage) {
462 return String::utf8([preferredLanguage UTF8String]).replace_char('-', '_');
463 }
464
465 NSString *localeIdentifier = [[NSLocale currentLocale] localeIdentifier];
466 return String::utf8([localeIdentifier UTF8String]).replace_char('-', '_');
467}
468
469Vector<String> OS_AppleEmbedded::get_preferred_locales() const {
470 Vector<String> out;
471 for (NSString *locale_code in [NSLocale preferredLanguages]) {
472 out.push_back(String([locale_code UTF8String]).replace_char('-', '_'));
473 }
474 if (out.is_empty()) {
475 NSString *localeIdentifier = [[NSLocale currentLocale] localeIdentifier];
476 out.push_back(String::utf8([localeIdentifier UTF8String]).replace_char('-', '_'));
477 }
478 return out;
479}
480
481String OS_AppleEmbedded::get_unique_id() const {
482 NSString *uuid = [UIDevice currentDevice].identifierForVendor.UUIDString;
483 return String::utf8([uuid UTF8String]);
484}
485
486struct _ModelInfo {
487 Vector<String> model;
488 String soc;
489};
490
491static const _ModelInfo _models[] = {
492 { { "iPhone1,1", "iPhone1,2", "iPod1,1" }, "Samsung S5L8900" },
493 { { "iPod2,1" }, "Samsung S5L8720" },
494 { { "iPhone2,1" }, "Samsung S5L8920" },
495 { { "iPod3,1" }, "Samsung S5L8922" },
496 { { "iPhone3,1", "iPhone3,2", "iPhone3,3", "iPad1,1", "iPad1,2", "iPod4,1", "AppleTV2,1" }, "Apple A4" },
497 { { "iPhone4,1", "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4", "iPad2,5", "iPad2,6", "iPad2,7", "iPod5,1", "AppleTV3,1", "AppleTV3,2" }, "Apple A5" },
498 { { "iPad3,1", "iPad3,2", "iPad3,3" }, "Apple A5X" },
499 { { "iPhone5,1", "iPhone5,2", "iPhone5,3", "iPhone5,4" }, "Apple A6" },
500 { { "iPad3,4", "iPad3,5", "iPad3,6" }, "Apple A6X" },
501 { { "iPhone6,1", "iPhone6,2", "iPad4,1", "iPad4,2", "iPad4,3", "iPad4,4", "iPad4,5", "iPad4,6", "iPad4,7", "iPad4,8", "iPad4,9" }, "Apple A7" },
502 { { "iPhone7,1", "iPhone7,2", "iPad5,1", "iPad5,2", "iPod7,1", "AppleTV5,3" }, "Apple A8" },
503 { { "iPad5,3", "iPad5,4" }, "Apple A8X" },
504 { { "iPhone8,1", "iPhone8,2", "iPhone8,4", "iPad6,11", "iPad6,12" }, "Apple A9" },
505 { { "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8" }, "Apple A9X" },
506 { { "iPhone9,1", "iPhone9,2", "iPhone9,3", "iPhone9,4", "iPad7,5", "iPad7,6", "iPad7,11", "iPad7,12", "iPod9,1" }, "Apple A10 Fusion" },
507 { { "iPad7,1", "iPad7,2", "iPad7,3", "iPad7,4", "AppleTV6,2" }, "Apple A10X Fusion" },
508 { { "iPhone10,1", "iPhone10,2", "iPhone10,3", "iPhone10,4", "iPhone10,5", "iPhone10,6" }, "Apple A11 Bionic" },
509 { { "iPhone11,2", "iPhone11,4", "iPhone11,6", "iPhone11,8", "iPad11,1", "iPad11,2", "iPad11,3", "iPad11,4", "iPad11,6", "iPad11,7", "AppleTV11,1" }, "Apple A12 Bionic" },
510 { { "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4", "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8" }, "Apple A12X Bionic" },
511 { { "iPad8,9", "iPad8,10", "iPad8,11", "iPad8,12" }, "Apple A12Z Bionic" },
512 { { "iPhone12,1", "iPhone12,3", "iPhone12,5", "iPhone12,8", "iPad12,1", "iPad12,2" }, "Apple A13 Bionic" },
513 { { "iPhone13,1", "iPhone13,2", "iPhone13,3", "iPhone13,4", "iPad13,1", "iPad13,2", "iPad13,18", "iPad13,19" }, "Apple A14 Bionic" },
514 { { "iPad13,4", "iPad13,5", "iPad13,6", "iPad13,7", "iPad13,8", "iPad13,9", "iPad13,10", "iPad13,11", "iPad13,16", "iPad13,17" }, "Apple M1" },
515 { { "iPhone14,2", "iPhone14,3", "iPhone14,4", "iPhone14,5", "iPhone14,6", "iPhone14,7", "iPhone14,8", "iPad14,1", "iPad14,2", "AppleTV14,1" }, "Apple A15 Bionic" },
516 { { "iPhone15,2", "iPhone15,3", "iPhone15,4", "iPhone15,5", "iPad15,7", "iPad15,8" }, "Apple A16 Bionic" },
517 { { "iPad14,3", "iPad14,4", "iPad14,5", "iPad14,6", "iPad14,8", "iPad14,9", "iPad14,10", "iPad14,11", "RealityDevice14,1" }, "Apple M2" },
518 { { "iPhone16,1", "iPhone16,2", "iPad16,1", "iPad16,2" }, "Apple A17 Pro" },
519 { { "iPad15,3", "iPad15,4", "iPad15,5", "iPad15,6" }, "Apple M3" },
520 { { "iPad16,3", "iPad16,4", "iPad16,5", "iPad16,6", "iPad16,8", "iPad16,9", "iPad16,10", "iPad16,11" }, "Apple M4" },
521 { { "iPad17,1", "iPad17,2", "iPad17,3", "iPad17,4", "RealityDevice17,1" }, "Apple M5" },
522 { { "iPhone17,3", "iPhone17,4", "iPhone17,5" }, "Apple A18" },
523 { { "iPhone17,1", "iPhone17,2" }, "Apple A18 Pro" },
524 { { "iPhone18,3", "iPhone18,5" }, "Apple A19" },
525 { { "iPhone18,1", "iPhone18,2", "iPhone18,4" }, "Apple A19 Pro" },
526 { { "iPhone19,2", "iPhone19,3", "iPhone19,4", "iPhone19,7", "iPad19,1", "iPad19,2" }, "Apple A20 Pro" },
527};
528
529String OS_AppleEmbedded::get_processor_name() const {
530#if defined(IOS_SIMULATOR) || defined(VISIONOS_SIMULATOR)
531 return "Simulator";
532#else
533 if (apple_embedded) {
534 String model = apple_embedded->get_model();
535 for (unsigned int i = 0; i < std::size(_models); i++) {
536 for (const String &m : _models[i].model) {
537 if (model.contains(m)) {
538 return _models[i].soc;
539 }
540 }
541 }
542 }
543#endif
544 return OS::get_processor_name();
545}
546
547Vector<String> OS_AppleEmbedded::get_system_fonts() const {
548 HashSet<String> font_names;
549 CFArrayRef fonts = CTFontManagerCopyAvailableFontFamilyNames();
550 if (fonts) {
551 for (CFIndex i = 0; i < CFArrayGetCount(fonts); i++) {
552 CFStringRef cf_name = (CFStringRef)CFArrayGetValueAtIndex(fonts, i);
553 if (cf_name && (CFStringGetLength(cf_name) > 0) && (CFStringCompare(cf_name, CFSTR("LastResort"), kCFCompareCaseInsensitive) != kCFCompareEqualTo) && (CFStringGetCharacterAtIndex(cf_name, 0) != '.')) {
554 NSString *ns_name = (__bridge NSString *)cf_name;
555 font_names.insert(String::utf8([ns_name UTF8String]));
556 }
557 }
558 CFRelease(fonts);
559 }
560
561 Vector<String> ret;
562 for (const String &E : font_names) {
563 ret.push_back(E);
564 }
565 return ret;
566}
567
568String OS_AppleEmbedded::_get_default_fontname(const String &p_font_name) const {
569 String font_name = p_font_name;
570 if (font_name.to_lower() == "sans-serif") {
571 font_name = "Helvetica";
572 } else if (font_name.to_lower() == "serif") {
573 font_name = "Times";
574 } else if (font_name.to_lower() == "monospace") {
575 font_name = "Courier";
576 } else if (font_name.to_lower() == "fantasy") {
577 font_name = "Papyrus";
578 } else if (font_name.to_lower() == "cursive") {
579 font_name = "Apple Chancery";
580 };
581 return font_name;
582}
583
584CGFloat OS_AppleEmbedded::_weight_to_ct(int p_weight) const {
585 if (p_weight < 150) {
586 return -0.80;
587 } else if (p_weight < 250) {
588 return -0.60;
589 } else if (p_weight < 350) {
590 return -0.40;
591 } else if (p_weight < 450) {
592 return 0.0;
593 } else if (p_weight < 550) {
594 return 0.23;
595 } else if (p_weight < 650) {
596 return 0.30;
597 } else if (p_weight < 750) {
598 return 0.40;
599 } else if (p_weight < 850) {
600 return 0.56;
601 } else if (p_weight < 925) {
602 return 0.62;
603 } else {
604 return 1.00;
605 }
606}
607
608CGFloat OS_AppleEmbedded::_stretch_to_ct(int p_stretch) const {
609 if (p_stretch < 56) {
610 return -0.5;
611 } else if (p_stretch < 69) {
612 return -0.37;
613 } else if (p_stretch < 81) {
614 return -0.25;
615 } else if (p_stretch < 93) {
616 return -0.13;
617 } else if (p_stretch < 106) {
618 return 0.0;
619 } else if (p_stretch < 137) {
620 return 0.13;
621 } else if (p_stretch < 144) {
622 return 0.25;
623 } else if (p_stretch < 162) {
624 return 0.37;
625 } else {
626 return 0.5;
627 }
628}
629
630Vector<String> OS_AppleEmbedded::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 {
631 Vector<String> ret;
632 String font_name = _get_default_fontname(p_font_name);
633
634 CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, font_name.utf8().get_data(), kCFStringEncodingUTF8);
635 CTFontSymbolicTraits traits = 0;
636 if (p_weight >= 700) {
637 traits |= kCTFontBoldTrait;
638 }
639 if (p_italic) {
640 traits |= kCTFontItalicTrait;
641 }
642 if (p_stretch < 100) {
643 traits |= kCTFontCondensedTrait;
644 } else if (p_stretch > 100) {
645 traits |= kCTFontExpandedTrait;
646 }
647
648 CFNumberRef sym_traits = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &traits);
649 CFMutableDictionaryRef traits_dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
650 CFDictionaryAddValue(traits_dict, kCTFontSymbolicTrait, sym_traits);
651
652 CGFloat weight = _weight_to_ct(p_weight);
653 CFNumberRef font_weight = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &weight);
654 CFDictionaryAddValue(traits_dict, kCTFontWeightTrait, font_weight);
655
656 CGFloat stretch = _stretch_to_ct(p_stretch);
657 CFNumberRef font_stretch = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &stretch);
658 CFDictionaryAddValue(traits_dict, kCTFontWidthTrait, font_stretch);
659
660 CFMutableDictionaryRef attributes = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
661 CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, name);
662 CFDictionaryAddValue(attributes, kCTFontTraitsAttribute, traits_dict);
663
664 CTFontDescriptorRef font = CTFontDescriptorCreateWithAttributes(attributes);
665 if (font) {
666 CTFontRef family = CTFontCreateWithFontDescriptor(font, 0, nullptr);
667 if (family) {
668 CFStringRef string = CFStringCreateWithCString(kCFAllocatorDefault, p_text.utf8().get_data(), kCFStringEncodingUTF8);
669 CFRange range = CFRangeMake(0, CFStringGetLength(string));
670 CTFontRef fallback_family = CTFontCreateForString(family, string, range);
671 if (fallback_family) {
672 CTFontDescriptorRef fallback_font = CTFontCopyFontDescriptor(fallback_family);
673 if (fallback_font) {
674 CFURLRef url = (CFURLRef)CTFontDescriptorCopyAttribute(fallback_font, kCTFontURLAttribute);
675 if (url) {
676 NSString *font_path = [NSString stringWithString:[(__bridge NSURL *)url path]];
677 ret.push_back(String::utf8([font_path UTF8String]));
678 CFRelease(url);
679 }
680 CFRelease(fallback_font);
681 }
682 CFRelease(fallback_family);
683 }
684 CFRelease(string);
685 CFRelease(family);
686 }
687 CFRelease(font);
688 }
689
690 CFRelease(attributes);
691 CFRelease(traits_dict);
692 CFRelease(sym_traits);
693 CFRelease(font_stretch);
694 CFRelease(font_weight);
695 CFRelease(name);
696
697 return ret;
698}
699
700String OS_AppleEmbedded::get_system_font_path(const String &p_font_name, int p_weight, int p_stretch, bool p_italic) const {
701 String ret;
702 String font_name = _get_default_fontname(p_font_name);
703
704 CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, font_name.utf8().get_data(), kCFStringEncodingUTF8);
705
706 CTFontSymbolicTraits traits = 0;
707 if (p_weight >= 700) {
708 traits |= kCTFontBoldTrait;
709 }
710 if (p_italic) {
711 traits |= kCTFontItalicTrait;
712 }
713 if (p_stretch < 100) {
714 traits |= kCTFontCondensedTrait;
715 } else if (p_stretch > 100) {
716 traits |= kCTFontExpandedTrait;
717 }
718
719 CFNumberRef sym_traits = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &traits);
720 CFMutableDictionaryRef traits_dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
721 CFDictionaryAddValue(traits_dict, kCTFontSymbolicTrait, sym_traits);
722
723 CGFloat weight = _weight_to_ct(p_weight);
724 CFNumberRef font_weight = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &weight);
725 CFDictionaryAddValue(traits_dict, kCTFontWeightTrait, font_weight);
726
727 CGFloat stretch = _stretch_to_ct(p_stretch);
728 CFNumberRef font_stretch = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &stretch);
729 CFDictionaryAddValue(traits_dict, kCTFontWidthTrait, font_stretch);
730
731 CFMutableDictionaryRef attributes = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
732 CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, name);
733 CFDictionaryAddValue(attributes, kCTFontTraitsAttribute, traits_dict);
734
735 CTFontDescriptorRef font = CTFontDescriptorCreateWithAttributes(attributes);
736 if (font) {
737 CFURLRef url = (CFURLRef)CTFontDescriptorCopyAttribute(font, kCTFontURLAttribute);
738 if (url) {
739 NSString *font_path = [NSString stringWithString:[(__bridge NSURL *)url path]];
740 ret = String::utf8([font_path UTF8String]);
741 CFRelease(url);
742 }
743 CFRelease(font);
744 }
745
746 CFRelease(attributes);
747 CFRelease(traits_dict);
748 CFRelease(sym_traits);
749 CFRelease(font_stretch);
750 CFRelease(font_weight);
751 CFRelease(name);
752
753 return ret;
754}
755
756void OS_AppleEmbedded::vibrate_handheld(int p_duration_ms, float p_amplitude) {
757 if (apple_embedded->supports_haptic_engine()) {
758 if (p_amplitude > 0.0) {
759 p_amplitude = CLAMP(p_amplitude, 0.0, 1.0);
760 }
761
762 apple_embedded->vibrate_haptic_engine((float)p_duration_ms / 1000.f, p_amplitude);
763 } else {
764 // iOS <13 does not support duration for vibration
765 AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
766 }
767}
768
769bool OS_AppleEmbedded::_check_internal_feature_support(const String &p_feature) {
770 if (p_feature == "system_fonts") {
771 return true;
772 }
773 if (p_feature == "mobile") {
774 return true;
775 }
776
777 return false;
778}
779
780Error OS_AppleEmbedded::setup_remote_filesystem(const String &p_server_host, int p_port, const String &p_password, String &r_project_path) {
781 r_project_path = OS::get_user_data_dir();
782 Error err = OS_Unix::setup_remote_filesystem(p_server_host, p_port, p_password, r_project_path);
783 if (err == OK) {
784 remote_fs_dir = r_project_path;
785 }
786 return err;
787}
788
789void OS_AppleEmbedded::audio_driver_start() {
790 // Dummy is the singleton when Core Audio init failed. Starting this unit would run a second mix thread.
791 if (AudioDriver::get_singleton() == &audio_driver) {
792 audio_driver.start();
793 }
794}
795
796void OS_AppleEmbedded::audio_driver_stop() {
797 if (AudioDriver::get_singleton() == &audio_driver) {
798 audio_driver.stop();
799 }
800}
801
802void OS_AppleEmbedded::on_focus_out() {
803 if (is_focused) {
804 is_focused = false;
805
806 if (DisplayServerAppleEmbedded::get_singleton()) {
807 DisplayServerAppleEmbedded::get_singleton()->send_window_event(DisplayServerEnums::WINDOW_EVENT_FOCUS_OUT);
808 }
809
810 if (AccessibilityServer::get_singleton()) {
811 AccessibilityServer::get_singleton()->set_window_focused(DisplayServerEnums::MAIN_WINDOW_ID, false);
812 }
813
814 if (OS::get_singleton()->get_main_loop()) {
815 OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT);
816 }
817
818 [GDTAppDelegateService.viewController.godotView stopRendering];
819
820 audio_driver_stop();
821 }
822}
823
824void OS_AppleEmbedded::on_focus_in() {
825 if (!is_focused) {
826 is_focused = true;
827
828 if (DisplayServerAppleEmbedded::get_singleton()) {
829 DisplayServerAppleEmbedded::get_singleton()->send_window_event(DisplayServerEnums::WINDOW_EVENT_FOCUS_IN);
830 }
831
832 if (AccessibilityServer::get_singleton()) {
833 AccessibilityServer::get_singleton()->set_window_focused(DisplayServerEnums::MAIN_WINDOW_ID, true);
834 }
835
836 if (OS::get_singleton()->get_main_loop()) {
837 OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN);
838 }
839
840 [GDTAppDelegateService.viewController.godotView startRendering];
841
842 audio_driver_start();
843 }
844}
845
846void OS_AppleEmbedded::on_enter_background() {
847 // Do not check for is_focused, because on_focus_out will always be fired first by applicationWillResignActive.
848
849 CameraServer *camera_server = CameraServer::get_singleton();
850 if (camera_server) {
851 camera_server->handle_application_pause();
852 }
853
854 if (OS::get_singleton()->get_main_loop()) {
855 OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_PAUSED);
856 }
857
858 on_focus_out();
859}
860
861void OS_AppleEmbedded::on_exit_background() {
862 if (!is_focused) {
863 on_focus_in();
864
865 if (OS::get_singleton()->get_main_loop()) {
866 OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_RESUMED);
867 }
868
869 CameraServer *camera_server = CameraServer::get_singleton();
870 if (camera_server) {
871 camera_server->handle_application_resume();
872 }
873 }
874}
875
876Rect2 OS_AppleEmbedded::calculate_boot_screen_rect(const Size2 &p_window_size, const Size2 &p_imgrect_size) const {
877 String scalemodestr = GLOBAL_GET("ios/launch_screen_image_mode");
878
879 if (scalemodestr == "scaleAspectFit") {
880 return fit_keep_aspect_centered(p_window_size, p_imgrect_size);
881 } else if (scalemodestr == "scaleAspectFill") {
882 return fit_keep_aspect_covered(p_window_size, p_imgrect_size);
883 } else if (scalemodestr == "scaleToFill") {
884 return Rect2(Point2(), p_window_size);
885 } else if (scalemodestr == "center") {
886 return OS_Unix::calculate_boot_screen_rect(p_window_size, p_imgrect_size);
887 } else {
888 WARN_PRINT(vformat("Boot screen scale mode mismatch between iOS and Godot: %s not supported", scalemodestr));
889 return OS_Unix::calculate_boot_screen_rect(p_window_size, p_imgrect_size);
890 }
891}
892
893bool OS_AppleEmbedded::request_permission(const String &p_name) {
894 if (p_name == "appleembedded.permission.AUDIO_RECORD") {
895 if (@available(iOS 17.0, *)) {
896 AVAudioApplicationRecordPermission permission = [AVAudioApplication sharedInstance].recordPermission;
897 if (permission == AVAudioApplicationRecordPermissionGranted) {
898 // Permission already granted, you can start recording.
899 return true;
900 } else if (permission == AVAudioApplicationRecordPermissionDenied) {
901 // Permission denied, or not yet granted.
902 return false;
903 } else {
904 // Request the permission, but for now return false as documented.
905 [AVAudioApplication requestRecordPermissionWithCompletionHandler:^(BOOL granted) {
906 get_main_loop()->emit_signal(SNAME("on_request_permissions_result"), p_name, granted);
907 }];
908 }
909 }
910 }
911 return false;
912}
913
914Vector<String> OS_AppleEmbedded::get_granted_permissions() const {
915 Vector<String> ret;
916
917 if (@available(iOS 17.0, *)) {
918 if ([AVAudioApplication sharedInstance].recordPermission == AVAudioApplicationRecordPermissionGranted) {
919 ret.push_back("appleembedded.permission.AUDIO_RECORD");
920 }
921 }
922 return ret;
923}
924#endif // APPLE_EMBEDDED_ENABLED