Debian Codegraph @

drivers/apple_embedded/os_apple_embedded.mm

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