os_android.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  1. /**************************************************************************/
  2. /* os_android.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "os_android.h"
  31. #include "dir_access_jandroid.h"
  32. #include "display_server_android.h"
  33. #include "file_access_android.h"
  34. #include "file_access_filesystem_jandroid.h"
  35. #include "java_godot_io_wrapper.h"
  36. #include "java_godot_wrapper.h"
  37. #include "net_socket_android.h"
  38. #include "core/config/project_settings.h"
  39. #include "core/extension/gdextension_manager.h"
  40. #include "core/io/xml_parser.h"
  41. #include "core/os/main_loop.h"
  42. #include "core/profiling/profiling.h"
  43. #include "drivers/unix/dir_access_unix.h"
  44. #include "drivers/unix/file_access_unix.h"
  45. #ifdef TOOLS_ENABLED
  46. #include "editor/editor_node.h"
  47. #include "editor/run/game_view_plugin.h"
  48. #endif
  49. #include "main/main.h"
  50. #include "scene/main/scene_tree.h"
  51. #include "servers/rendering/rendering_server.h"
  52. #include <dlfcn.h>
  53. #include <sys/system_properties.h>
  54. const char *OS_Android::ANDROID_EXEC_PATH = "apk";
  55. String _remove_symlink(const String &dir) {
  56. // Workaround for Android 6.0+ using a symlink.
  57. // Save the current directory.
  58. char current_dir_name[2048];
  59. getcwd(current_dir_name, 2048);
  60. // Change directory to the external data directory.
  61. chdir(dir.utf8().get_data());
  62. // Get the actual directory without the potential symlink.
  63. char dir_name_without_symlink[2048];
  64. getcwd(dir_name_without_symlink, 2048);
  65. // Convert back to a String.
  66. String dir_without_symlink(dir_name_without_symlink);
  67. // Restore original current directory.
  68. chdir(current_dir_name);
  69. return dir_without_symlink;
  70. }
  71. #ifdef TOOLS_ENABLED
  72. _FORCE_INLINE_ static GameViewPlugin *_get_game_view_plugin() {
  73. ERR_FAIL_NULL_V(EditorNode::get_singleton(), nullptr);
  74. ERR_FAIL_NULL_V(EditorNode::get_singleton()->get_editor_main_screen(), nullptr);
  75. return Object::cast_to<GameViewPlugin>(EditorNode::get_singleton()->get_editor_main_screen()->get_plugin_by_name("Game"));
  76. }
  77. #endif
  78. class AndroidLogger : public Logger {
  79. public:
  80. virtual void logv(const char *p_format, va_list p_list, bool p_err) {
  81. __android_log_vprint(p_err ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, "godot", p_format, p_list);
  82. }
  83. virtual ~AndroidLogger() {}
  84. };
  85. void OS_Android::alert(const String &p_alert, const String &p_title) {
  86. ERR_FAIL_NULL(godot_java);
  87. godot_java->alert(p_alert, p_title);
  88. }
  89. void OS_Android::initialize_core() {
  90. OS_Unix::initialize_core();
  91. #ifdef TOOLS_ENABLED
  92. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_RESOURCES);
  93. #else
  94. if (use_apk_expansion) {
  95. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_RESOURCES);
  96. } else {
  97. FileAccess::make_default<FileAccessAndroid>(FileAccess::ACCESS_RESOURCES);
  98. }
  99. #endif
  100. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_USERDATA);
  101. FileAccess::make_default<FileAccessFilesystemJAndroid>(FileAccess::ACCESS_FILESYSTEM);
  102. #ifdef TOOLS_ENABLED
  103. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_RESOURCES);
  104. #else
  105. if (use_apk_expansion) {
  106. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_RESOURCES);
  107. } else {
  108. DirAccess::make_default<DirAccessJAndroid>(DirAccess::ACCESS_RESOURCES);
  109. }
  110. #endif
  111. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_USERDATA);
  112. DirAccess::make_default<DirAccessJAndroid>(DirAccess::ACCESS_FILESYSTEM);
  113. NetSocketAndroid::make_default();
  114. }
  115. void OS_Android::initialize() {
  116. initialize_core();
  117. }
  118. void OS_Android::initialize_joypads() {
  119. Input::get_singleton()->set_fallback_mapping(godot_java->get_input_fallback_mapping());
  120. // This queries/updates the currently connected devices/joypads.
  121. godot_java->init_input_devices();
  122. }
  123. void OS_Android::set_main_loop(MainLoop *p_main_loop) {
  124. main_loop = p_main_loop;
  125. }
  126. void OS_Android::delete_main_loop() {
  127. if (main_loop) {
  128. memdelete(main_loop);
  129. main_loop = nullptr;
  130. }
  131. }
  132. void OS_Android::finalize() {
  133. }
  134. OS_Android *OS_Android::get_singleton() {
  135. return static_cast<OS_Android *>(OS::get_singleton());
  136. }
  137. GodotJavaWrapper *OS_Android::get_godot_java() {
  138. return godot_java;
  139. }
  140. GodotIOJavaWrapper *OS_Android::get_godot_io_java() {
  141. return godot_io_java;
  142. }
  143. bool OS_Android::request_permission(const String &p_name) {
  144. return godot_java->request_permission(p_name);
  145. }
  146. bool OS_Android::request_permissions() {
  147. return godot_java->request_permissions();
  148. }
  149. Vector<String> OS_Android::get_granted_permissions() const {
  150. return godot_java->get_granted_permissions();
  151. }
  152. bool OS_Android::copy_dynamic_library(const String &p_library_path, const String &p_target_dir, String *r_copy_path) {
  153. if (!FileAccess::exists(p_library_path)) {
  154. return false;
  155. }
  156. Ref<DirAccess> da_ref = DirAccess::create_for_path(p_library_path);
  157. if (da_ref.is_null()) {
  158. return false;
  159. }
  160. String copy_path = p_target_dir.path_join(p_library_path.get_file());
  161. bool copy_exists = FileAccess::exists(copy_path);
  162. if (copy_exists) {
  163. print_verbose("Deleting existing library copy " + copy_path);
  164. if (da_ref->remove(copy_path) != OK) {
  165. print_verbose("Unable to delete " + copy_path);
  166. }
  167. }
  168. print_verbose("Copying " + p_library_path + " to " + p_target_dir);
  169. Error create_dir_result = da_ref->make_dir_recursive(p_target_dir);
  170. if (create_dir_result == OK || create_dir_result == ERR_ALREADY_EXISTS) {
  171. copy_exists = da_ref->copy(p_library_path, copy_path) == OK;
  172. }
  173. if (copy_exists && r_copy_path != nullptr) {
  174. *r_copy_path = copy_path;
  175. }
  176. return copy_exists;
  177. }
  178. Error OS_Android::open_dynamic_library(const String &p_path, void *&p_library_handle, GDExtensionData *p_data) {
  179. String path = p_path;
  180. bool so_file_exists = true;
  181. if (!FileAccess::exists(path)) {
  182. path = p_path.get_file();
  183. so_file_exists = false;
  184. }
  185. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  186. if (!p_library_handle && so_file_exists) {
  187. // The library (and its dependencies) may be on the sdcard and thus inaccessible.
  188. // Try to copy to the internal directory for access.
  189. const String dynamic_library_path = get_dynamic_libraries_path();
  190. if (p_data != nullptr && p_data->library_dependencies != nullptr && !p_data->library_dependencies->is_empty()) {
  191. // Copy the library dependencies
  192. print_verbose("Copying library dependencies..");
  193. for (const String &library_dependency_path : *p_data->library_dependencies) {
  194. String internal_library_dependency_path;
  195. if (!copy_dynamic_library(library_dependency_path, dynamic_library_path.path_join(library_dependency_path.get_base_dir()), &internal_library_dependency_path)) {
  196. ERR_PRINT(vformat("Unable to copy library dependency %s", library_dependency_path));
  197. } else {
  198. void *lib_dependency_handle = dlopen(internal_library_dependency_path.utf8().get_data(), RTLD_NOW);
  199. if (!lib_dependency_handle) {
  200. ERR_PRINT(vformat("Can't open dynamic library dependency: %s. Error: %s.", internal_library_dependency_path, dlerror()));
  201. }
  202. }
  203. }
  204. }
  205. String internal_path;
  206. print_verbose("Copying library " + p_path);
  207. const bool internal_so_file_exists = copy_dynamic_library(p_path, dynamic_library_path.path_join(p_path.get_base_dir()), &internal_path);
  208. if (internal_so_file_exists) {
  209. print_verbose("Opening library " + internal_path);
  210. p_library_handle = dlopen(internal_path.utf8().get_data(), RTLD_NOW);
  211. if (p_library_handle) {
  212. path = internal_path;
  213. }
  214. }
  215. }
  216. ERR_FAIL_NULL_V_MSG(p_library_handle, ERR_CANT_OPEN, vformat("Can't open dynamic library: %s. Error: %s.", p_path, dlerror()));
  217. if (p_data != nullptr && p_data->r_resolved_path != nullptr) {
  218. *p_data->r_resolved_path = path;
  219. }
  220. return OK;
  221. }
  222. String OS_Android::get_name() const {
  223. return "Android";
  224. }
  225. String OS_Android::get_system_property(const char *key) const {
  226. String value;
  227. char value_str[PROP_VALUE_MAX];
  228. if (__system_property_get(key, value_str)) {
  229. value = String(value_str);
  230. }
  231. return value;
  232. }
  233. String OS_Android::get_distribution_name() const {
  234. if (!get_system_property("ro.havoc.version").is_empty()) {
  235. return "Havoc OS";
  236. } else if (!get_system_property("org.pex.version").is_empty()) { // Putting before "Pixel Experience", because it's derivating from it.
  237. return "Pixel Extended";
  238. } else if (!get_system_property("org.pixelexperience.version").is_empty()) {
  239. return "Pixel Experience";
  240. } else if (!get_system_property("ro.potato.version").is_empty()) {
  241. return "POSP";
  242. } else if (!get_system_property("ro.xtended.version").is_empty()) {
  243. return "Project-Xtended";
  244. } else if (!get_system_property("org.evolution.version").is_empty()) {
  245. return "Evolution X";
  246. } else if (!get_system_property("ro.corvus.version").is_empty()) {
  247. return "Corvus-Q";
  248. } else if (!get_system_property("ro.pa.version").is_empty()) {
  249. return "Paranoid Android";
  250. } else if (!get_system_property("ro.crdroid.version").is_empty()) {
  251. return "crDroid Android";
  252. } else if (!get_system_property("ro.syberia.version").is_empty()) {
  253. return "Syberia Project";
  254. } else if (!get_system_property("ro.arrow.version").is_empty()) {
  255. return "ArrowOS";
  256. } else if (!get_system_property("ro.lineage.version").is_empty()) { // Putting LineageOS last, just in case any derivative writes to "ro.lineage.version".
  257. return "LineageOS";
  258. }
  259. if (!get_system_property("ro.modversion").is_empty()) { // Handles other Android custom ROMs.
  260. return vformat("%s %s", get_name(), "Custom ROM");
  261. }
  262. // Handles stock Android.
  263. return get_name();
  264. }
  265. String OS_Android::get_version() const {
  266. const Vector<const char *> roms = { "ro.havoc.version", "org.pex.version", "org.pixelexperience.version",
  267. "ro.potato.version", "ro.xtended.version", "org.evolution.version", "ro.corvus.version", "ro.pa.version",
  268. "ro.crdroid.version", "ro.syberia.version", "ro.arrow.version", "ro.lineage.version" };
  269. for (int i = 0; i < roms.size(); i++) {
  270. String rom_version = get_system_property(roms[i]);
  271. if (!rom_version.is_empty()) {
  272. return rom_version;
  273. }
  274. }
  275. String mod_version = get_system_property("ro.modversion"); // Handles other Android custom ROMs.
  276. if (!mod_version.is_empty()) {
  277. return mod_version;
  278. }
  279. // Handles stock Android.
  280. String sdk_version = get_system_property("ro.build.version.sdk");
  281. String build = get_system_property("ro.build.version.incremental");
  282. if (!sdk_version.is_empty()) {
  283. if (!build.is_empty()) {
  284. return vformat("%s.%s", sdk_version, build);
  285. }
  286. return sdk_version;
  287. }
  288. return "";
  289. }
  290. String OS_Android::get_version_alias() const {
  291. String release = get_system_property("ro.build.version.release_or_codename");
  292. String sdk_version = get_system_property("ro.build.version.sdk");
  293. String build = get_system_property("ro.build.version.incremental");
  294. return vformat("%s (SDK %s build %s)", release, sdk_version, build);
  295. }
  296. MainLoop *OS_Android::get_main_loop() const {
  297. return main_loop;
  298. }
  299. void OS_Android::main_loop_begin() {
  300. if (main_loop) {
  301. main_loop->initialize();
  302. }
  303. #ifdef TOOLS_ENABLED
  304. if (Engine::get_singleton()->is_editor_hint()) {
  305. GameViewPlugin *game_view_plugin = _get_game_view_plugin();
  306. if (game_view_plugin != nullptr) {
  307. game_view_plugin->connect("main_screen_changed", callable_mp_static(&OS_Android::_on_main_screen_changed));
  308. }
  309. }
  310. #endif
  311. }
  312. bool OS_Android::main_loop_iterate(bool *r_should_swap_buffers) {
  313. GodotProfileFrameMark;
  314. GodotProfileZone("OS_Android::main_loop_iterate");
  315. if (!main_loop) {
  316. return false;
  317. }
  318. DisplayServerAndroid::get_singleton()->reset_swap_buffers_flag();
  319. DisplayServerAndroid::get_singleton()->process_events();
  320. uint64_t current_frames_drawn = Engine::get_singleton()->get_frames_drawn();
  321. bool exit = Main::iteration();
  322. if (r_should_swap_buffers) {
  323. *r_should_swap_buffers = !is_in_low_processor_usage_mode() ||
  324. DisplayServerAndroid::get_singleton()->should_swap_buffers() ||
  325. RenderingServer::get_singleton()->has_changed() ||
  326. current_frames_drawn != Engine::get_singleton()->get_frames_drawn();
  327. }
  328. return exit;
  329. }
  330. void OS_Android::main_loop_end() {
  331. #ifdef TOOLS_ENABLED
  332. if (Engine::get_singleton()->is_editor_hint()) {
  333. GameViewPlugin *game_view_plugin = _get_game_view_plugin();
  334. if (game_view_plugin != nullptr) {
  335. game_view_plugin->disconnect("main_screen_changed", callable_mp_static(&OS_Android::_on_main_screen_changed));
  336. }
  337. }
  338. #endif
  339. if (main_loop) {
  340. SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop);
  341. if (scene_tree) {
  342. scene_tree->quit();
  343. }
  344. main_loop->finalize();
  345. }
  346. }
  347. #ifdef TOOLS_ENABLED
  348. void OS_Android::_on_main_screen_changed(const String &p_screen_name) {
  349. if (OS_Android::get_singleton() != nullptr && OS_Android::get_singleton()->get_godot_java() != nullptr) {
  350. OS_Android::get_singleton()->get_godot_java()->on_editor_workspace_selected(p_screen_name);
  351. }
  352. }
  353. #endif
  354. void OS_Android::main_loop_focusout() {
  355. DisplayServerAndroid::get_singleton()->send_window_event(DisplayServer::WINDOW_EVENT_FOCUS_OUT);
  356. if (OS::get_singleton()->get_main_loop()) {
  357. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT);
  358. }
  359. audio_driver_android.set_pause(true);
  360. }
  361. void OS_Android::main_loop_focusin() {
  362. DisplayServerAndroid::get_singleton()->send_window_event(DisplayServer::WINDOW_EVENT_FOCUS_IN);
  363. if (OS::get_singleton()->get_main_loop()) {
  364. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN);
  365. }
  366. audio_driver_android.set_pause(false);
  367. }
  368. Error OS_Android::shell_open(const String &p_uri) {
  369. return godot_io_java->open_uri(p_uri);
  370. }
  371. String OS_Android::get_resource_dir() const {
  372. #ifdef TOOLS_ENABLED
  373. return OS_Unix::get_resource_dir();
  374. #else
  375. if (remote_fs_dir.is_empty()) {
  376. return "/"; // Android has its own filesystem for resources inside the APK
  377. } else {
  378. return remote_fs_dir;
  379. }
  380. #endif
  381. }
  382. String OS_Android::get_locale() const {
  383. String locale = godot_io_java->get_locale();
  384. if (!locale.is_empty()) {
  385. return locale;
  386. }
  387. return OS_Unix::get_locale();
  388. }
  389. String OS_Android::get_model_name() const {
  390. String model = godot_io_java->get_model();
  391. if (!model.is_empty()) {
  392. return model;
  393. }
  394. return OS_Unix::get_model_name();
  395. }
  396. String OS_Android::get_data_path() const {
  397. return OS::get_user_data_dir();
  398. }
  399. void OS_Android::_load_system_font_config() const {
  400. font_aliases.clear();
  401. fonts.clear();
  402. font_names.clear();
  403. Ref<XMLParser> parser;
  404. parser.instantiate();
  405. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  406. String root = String(getenv("ANDROID_ROOT")).path_join("fonts");
  407. Error err = parser->open(String(getenv("ANDROID_ROOT")).path_join("/etc/fonts.xml"));
  408. if (err == OK) {
  409. bool in_font_node = false;
  410. String fb, fn;
  411. FontInfo fi;
  412. while (parser->read() == OK) {
  413. if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
  414. in_font_node = false;
  415. if (parser->get_node_name() == "familyset") {
  416. int ver = parser->has_attribute("version") ? parser->get_named_attribute_value("version").to_int() : 0;
  417. if (ver < 21) {
  418. ERR_PRINT(vformat("Unsupported font config version %s", ver));
  419. break;
  420. }
  421. } else if (parser->get_node_name() == "alias") {
  422. String name = parser->has_attribute("name") ? parser->get_named_attribute_value("name").strip_edges() : String();
  423. String to = parser->has_attribute("to") ? parser->get_named_attribute_value("to").strip_edges() : String();
  424. if (!name.is_empty() && !to.is_empty()) {
  425. font_aliases[name] = to;
  426. }
  427. } else if (parser->get_node_name() == "family") {
  428. fn = parser->has_attribute("name") ? parser->get_named_attribute_value("name").strip_edges() : String();
  429. String lang_code = parser->has_attribute("lang") ? parser->get_named_attribute_value("lang").strip_edges() : String();
  430. Vector<String> lang_codes = lang_code.split(",");
  431. for (int i = 0; i < lang_codes.size(); i++) {
  432. Vector<String> lang_code_elements = lang_codes[i].split("-");
  433. if (lang_code_elements.size() >= 1 && lang_code_elements[0] != "und") {
  434. // Add missing script codes.
  435. if (lang_code_elements[0] == "ko") {
  436. fi.script.insert("Hani");
  437. fi.script.insert("Hang");
  438. }
  439. if (lang_code_elements[0] == "ja") {
  440. fi.script.insert("Hani");
  441. fi.script.insert("Kana");
  442. fi.script.insert("Hira");
  443. }
  444. if (!lang_code_elements[0].is_empty()) {
  445. fi.lang.insert(lang_code_elements[0]);
  446. }
  447. }
  448. if (lang_code_elements.size() >= 2) {
  449. // Add common codes for variants and remove variants not supported by HarfBuzz/ICU.
  450. if (lang_code_elements[1] == "Aran") {
  451. fi.script.insert("Arab");
  452. }
  453. if (lang_code_elements[1] == "Cyrs") {
  454. fi.script.insert("Cyrl");
  455. }
  456. if (lang_code_elements[1] == "Hanb") {
  457. fi.script.insert("Hani");
  458. fi.script.insert("Bopo");
  459. }
  460. if (lang_code_elements[1] == "Hans" || lang_code_elements[1] == "Hant") {
  461. fi.script.insert("Hani");
  462. }
  463. if (lang_code_elements[1] == "Syrj" || lang_code_elements[1] == "Syre" || lang_code_elements[1] == "Syrn") {
  464. fi.script.insert("Syrc");
  465. }
  466. if (!lang_code_elements[1].is_empty() && lang_code_elements[1] != "Zsym" && lang_code_elements[1] != "Zsye" && lang_code_elements[1] != "Zmth") {
  467. fi.script.insert(lang_code_elements[1]);
  468. }
  469. }
  470. }
  471. } else if (parser->get_node_name() == "font") {
  472. in_font_node = true;
  473. fb = parser->has_attribute("fallbackFor") ? parser->get_named_attribute_value("fallbackFor").strip_edges() : String();
  474. fi.weight = parser->has_attribute("weight") ? parser->get_named_attribute_value("weight").to_int() : 400;
  475. fi.italic = parser->has_attribute("style") && parser->get_named_attribute_value("style").strip_edges() == "italic";
  476. }
  477. }
  478. if (parser->get_node_type() == XMLParser::NODE_TEXT) {
  479. if (in_font_node) {
  480. fi.filename = parser->get_node_data().strip_edges();
  481. fi.font_name = fn;
  482. if (da->file_exists(root.path_join(fi.filename))) {
  483. if (!fb.is_empty() && fn.is_empty()) {
  484. fi.font_name = fb;
  485. fi.priority = 2;
  486. }
  487. if (fi.font_name.is_empty()) {
  488. fi.font_name = "sans-serif";
  489. fi.priority = 5;
  490. }
  491. if (fi.font_name.ends_with("-condensed")) {
  492. fi.stretch = 75;
  493. fi.font_name = fi.font_name.trim_suffix("-condensed");
  494. }
  495. fonts.push_back(fi);
  496. font_names.insert(fi.font_name);
  497. }
  498. }
  499. }
  500. if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END) {
  501. in_font_node = false;
  502. if (parser->get_node_name() == "font") {
  503. fb = String();
  504. fi.font_name = String();
  505. fi.priority = 0;
  506. fi.weight = 400;
  507. fi.stretch = 100;
  508. fi.italic = false;
  509. } else if (parser->get_node_name() == "family") {
  510. fi = FontInfo();
  511. fn = String();
  512. }
  513. }
  514. }
  515. parser->close();
  516. } else {
  517. ERR_PRINT("Unable to load font config");
  518. }
  519. font_config_loaded = true;
  520. }
  521. Vector<String> OS_Android::get_system_fonts() const {
  522. if (!font_config_loaded) {
  523. _load_system_font_config();
  524. }
  525. Vector<String> ret;
  526. for (const String &E : font_names) {
  527. ret.push_back(E);
  528. }
  529. return ret;
  530. }
  531. Vector<String> OS_Android::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 {
  532. if (!font_config_loaded) {
  533. _load_system_font_config();
  534. }
  535. String font_name = p_font_name.to_lower();
  536. if (font_aliases.has(font_name)) {
  537. font_name = font_aliases[font_name];
  538. }
  539. String root = String(getenv("ANDROID_ROOT")).path_join("fonts");
  540. String lang_prefix = p_locale.get_slicec('_', 0);
  541. Vector<String> ret;
  542. int best_score = 0;
  543. for (const List<FontInfo>::Element *E = fonts.front(); E; E = E->next()) {
  544. int score = 0;
  545. if (!E->get().script.is_empty() && !p_script.is_empty() && !E->get().script.has(p_script)) {
  546. continue;
  547. }
  548. float sim = E->get().font_name.similarity(font_name);
  549. if (sim > 0.0) {
  550. score += (60 * sim + 5 - E->get().priority);
  551. }
  552. if (E->get().lang.has(p_locale)) {
  553. score += 120;
  554. } else if (E->get().lang.has(lang_prefix)) {
  555. score += 115;
  556. }
  557. if (E->get().script.has(p_script)) {
  558. score += 240;
  559. }
  560. score += (20 - Math::abs(E->get().weight - p_weight) / 50);
  561. score += (20 - Math::abs(E->get().stretch - p_stretch) / 10);
  562. if (E->get().italic == p_italic) {
  563. score += 30;
  564. }
  565. if (score > best_score) {
  566. best_score = score;
  567. if (!ret.has(root.path_join(E->get().filename))) {
  568. ret.insert(0, root.path_join(E->get().filename));
  569. }
  570. } else if (score == best_score || E->get().script.is_empty()) {
  571. if (!ret.has(root.path_join(E->get().filename))) {
  572. ret.push_back(root.path_join(E->get().filename));
  573. }
  574. }
  575. if (score >= 490) {
  576. break; // Perfect match.
  577. }
  578. }
  579. return ret;
  580. }
  581. String OS_Android::get_system_font_path(const String &p_font_name, int p_weight, int p_stretch, bool p_italic) const {
  582. if (!font_config_loaded) {
  583. _load_system_font_config();
  584. }
  585. String font_name = p_font_name.to_lower();
  586. if (font_aliases.has(font_name)) {
  587. font_name = font_aliases[font_name];
  588. }
  589. String root = String(getenv("ANDROID_ROOT")).path_join("fonts");
  590. int best_score = 0;
  591. const List<FontInfo>::Element *best_match = nullptr;
  592. for (const List<FontInfo>::Element *E = fonts.front(); E; E = E->next()) {
  593. int score = 0;
  594. if (E->get().font_name == font_name) {
  595. score += (65 - E->get().priority);
  596. }
  597. score += (20 - Math::abs(E->get().weight - p_weight) / 50);
  598. score += (20 - Math::abs(E->get().stretch - p_stretch) / 10);
  599. if (E->get().italic == p_italic) {
  600. score += 30;
  601. }
  602. if (score >= 60 && score > best_score) {
  603. best_score = score;
  604. best_match = E;
  605. }
  606. if (score >= 140) {
  607. break; // Perfect match.
  608. }
  609. }
  610. if (best_match) {
  611. return root.path_join(best_match->get().filename);
  612. }
  613. return String();
  614. }
  615. String OS_Android::get_executable_path() const {
  616. // Since unix process creation is restricted on Android, we bypass
  617. // OS_Unix::get_executable_path() so we can return ANDROID_EXEC_PATH.
  618. // Detection of ANDROID_EXEC_PATH allows to handle process creation in an Android compliant
  619. // manner.
  620. return OS::get_executable_path();
  621. }
  622. String OS_Android::get_user_data_dir(const String &p_user_dir) const {
  623. if (!data_dir_cache.is_empty()) {
  624. return data_dir_cache;
  625. }
  626. String data_dir = godot_io_java->get_user_data_dir(p_user_dir);
  627. if (!data_dir.is_empty()) {
  628. data_dir_cache = _remove_symlink(data_dir);
  629. return data_dir_cache;
  630. }
  631. return ".";
  632. }
  633. String OS_Android::get_dynamic_libraries_path() const {
  634. return get_cache_path().path_join("dynamic_libraries");
  635. }
  636. String OS_Android::get_cache_path() const {
  637. if (!cache_dir_cache.is_empty()) {
  638. return cache_dir_cache;
  639. }
  640. String cache_dir = godot_io_java->get_cache_dir();
  641. if (!cache_dir.is_empty()) {
  642. cache_dir_cache = _remove_symlink(cache_dir);
  643. return cache_dir_cache;
  644. }
  645. return ".";
  646. }
  647. String OS_Android::get_temp_path() const {
  648. if (!temp_dir_cache.is_empty()) {
  649. return temp_dir_cache;
  650. }
  651. String temp_dir = godot_io_java->get_temp_dir();
  652. if (!temp_dir.is_empty()) {
  653. temp_dir_cache = _remove_symlink(temp_dir);
  654. return temp_dir_cache;
  655. }
  656. return ".";
  657. }
  658. String OS_Android::get_unique_id() const {
  659. String unique_id = godot_io_java->get_unique_id();
  660. if (!unique_id.is_empty()) {
  661. return unique_id;
  662. }
  663. return OS::get_unique_id();
  664. }
  665. String OS_Android::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  666. return godot_io_java->get_system_dir(p_dir, p_shared_storage);
  667. }
  668. Error OS_Android::move_to_trash(const String &p_path) {
  669. Ref<DirAccess> da_ref = DirAccess::create_for_path(p_path);
  670. if (da_ref.is_null()) {
  671. return FAILED;
  672. }
  673. // Check if it's a directory
  674. if (da_ref->dir_exists(p_path)) {
  675. Error err = da_ref->change_dir(p_path);
  676. if (err) {
  677. return err;
  678. }
  679. // This is directory, let's erase its contents
  680. err = da_ref->erase_contents_recursive();
  681. if (err) {
  682. return err;
  683. }
  684. // Remove the top directory
  685. return da_ref->remove(p_path);
  686. } else if (da_ref->file_exists(p_path)) {
  687. // This is a file, let's remove it.
  688. return da_ref->remove(p_path);
  689. } else {
  690. return FAILED;
  691. }
  692. }
  693. void OS_Android::set_display_size(const Size2i &p_size) {
  694. display_size = p_size;
  695. }
  696. Size2i OS_Android::get_display_size() const {
  697. return display_size;
  698. }
  699. void OS_Android::set_opengl_extensions(const char *p_gl_extensions) {
  700. #if defined(GLES3_ENABLED)
  701. ERR_FAIL_NULL(p_gl_extensions);
  702. gl_extensions = p_gl_extensions;
  703. #endif
  704. }
  705. void OS_Android::set_native_window(ANativeWindow *p_native_window) {
  706. #if defined(VULKAN_ENABLED)
  707. native_window = p_native_window;
  708. #endif
  709. }
  710. ANativeWindow *OS_Android::get_native_window() const {
  711. #if defined(VULKAN_ENABLED)
  712. return native_window;
  713. #else
  714. return nullptr;
  715. #endif
  716. }
  717. void OS_Android::vibrate_handheld(int p_duration_ms, float p_amplitude) {
  718. godot_java->vibrate(p_duration_ms, p_amplitude);
  719. }
  720. String OS_Android::get_config_path() const {
  721. return OS::get_user_data_dir().path_join("config");
  722. }
  723. void OS_Android::benchmark_begin_measure(const String &p_context, const String &p_what) {
  724. #ifdef TOOLS_ENABLED
  725. godot_java->begin_benchmark_measure(p_context, p_what);
  726. #endif
  727. }
  728. void OS_Android::benchmark_end_measure(const String &p_context, const String &p_what) {
  729. #ifdef TOOLS_ENABLED
  730. godot_java->end_benchmark_measure(p_context, p_what);
  731. #endif
  732. }
  733. void OS_Android::benchmark_dump() {
  734. #ifdef TOOLS_ENABLED
  735. if (!is_use_benchmark_set()) {
  736. return;
  737. }
  738. godot_java->dump_benchmark(get_benchmark_file());
  739. #endif
  740. }
  741. #ifdef TOOLS_ENABLED
  742. Error OS_Android::sign_apk(const String &p_input_path, const String &p_output_path, const String &p_keystore_path, const String &p_keystore_user, const String &p_keystore_password) {
  743. return godot_java->sign_apk(p_input_path, p_output_path, p_keystore_path, p_keystore_user, p_keystore_password);
  744. }
  745. Error OS_Android::verify_apk(const String &p_apk_path) {
  746. return godot_java->verify_apk(p_apk_path);
  747. }
  748. #endif
  749. bool OS_Android::_check_internal_feature_support(const String &p_feature) {
  750. if (p_feature == "macos" || p_feature == "web_ios" || p_feature == "web_macos" || p_feature == "windows") {
  751. return false;
  752. }
  753. if (p_feature == "system_fonts") {
  754. return true;
  755. }
  756. if (p_feature == "mobile") {
  757. return true;
  758. }
  759. #if defined(__aarch64__)
  760. if (p_feature == "arm64-v8a" || p_feature == "arm64") {
  761. return true;
  762. }
  763. #elif defined(__ARM_ARCH_7A__)
  764. if (p_feature == "armeabi-v7a" || p_feature == "armeabi" || p_feature == "arm32") {
  765. return true;
  766. }
  767. #elif defined(__arm__)
  768. if (p_feature == "armeabi" || p_feature == "arm") {
  769. return true;
  770. }
  771. #endif
  772. if (godot_java->check_internal_feature_support(p_feature)) {
  773. return true;
  774. }
  775. return false;
  776. }
  777. OS_Android::OS_Android(GodotJavaWrapper *p_godot_java, GodotIOJavaWrapper *p_godot_io_java, bool p_use_apk_expansion) {
  778. display_size.width = DEFAULT_WINDOW_WIDTH;
  779. display_size.height = DEFAULT_WINDOW_HEIGHT;
  780. use_apk_expansion = p_use_apk_expansion;
  781. main_loop = nullptr;
  782. #if defined(GLES3_ENABLED)
  783. gl_extensions = nullptr;
  784. #endif
  785. #if defined(VULKAN_ENABLED)
  786. native_window = nullptr;
  787. #endif
  788. godot_java = p_godot_java;
  789. godot_io_java = p_godot_io_java;
  790. Vector<Logger *> loggers;
  791. loggers.push_back(memnew(AndroidLogger));
  792. _set_logger(memnew(CompositeLogger(loggers)));
  793. AudioDriverManager::add_driver(&audio_driver_android);
  794. DisplayServerAndroid::register_android_driver();
  795. }
  796. Error OS_Android::execute(const String &p_path, const List<String> &p_arguments, String *r_pipe, int *r_exitcode, bool read_stderr, Mutex *p_pipe_mutex, bool p_open_console) {
  797. if (p_path == ANDROID_EXEC_PATH) {
  798. return create_instance(p_arguments);
  799. } else {
  800. return OS_Unix::execute(p_path, p_arguments, r_pipe, r_exitcode, read_stderr, p_pipe_mutex, p_open_console);
  801. }
  802. }
  803. Error OS_Android::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
  804. if (p_path == ANDROID_EXEC_PATH) {
  805. return create_instance(p_arguments, r_child_id);
  806. } else {
  807. return OS_Unix::create_process(p_path, p_arguments, r_child_id, p_open_console);
  808. }
  809. }
  810. Error OS_Android::create_instance(const List<String> &p_arguments, ProcessID *r_child_id) {
  811. int instance_id = godot_java->create_new_godot_instance(p_arguments);
  812. if (instance_id == -1) {
  813. return FAILED;
  814. }
  815. if (r_child_id) {
  816. *r_child_id = instance_id;
  817. }
  818. return OK;
  819. }
  820. Error OS_Android::kill(const ProcessID &p_pid) {
  821. if (godot_java->force_quit(nullptr, p_pid)) {
  822. return OK;
  823. }
  824. return OS_Unix::kill(p_pid);
  825. }
  826. String OS_Android::get_system_ca_certificates() {
  827. return godot_java->get_ca_certificates();
  828. }
  829. Error OS_Android::setup_remote_filesystem(const String &p_server_host, int p_port, const String &p_password, String &r_project_path) {
  830. r_project_path = OS::get_user_data_dir();
  831. Error err = OS_Unix::setup_remote_filesystem(p_server_host, p_port, p_password, r_project_path);
  832. if (err == OK) {
  833. remote_fs_dir = r_project_path;
  834. FileAccess::make_default<FileAccessFilesystemJAndroid>(FileAccess::ACCESS_RESOURCES);
  835. }
  836. return err;
  837. }
  838. void OS_Android::load_platform_gdextensions() const {
  839. Vector<String> extension_list_config_file = godot_java->get_gdextension_list_config_file();
  840. for (String config_file_path : extension_list_config_file) {
  841. GDExtensionManager::LoadStatus err = GDExtensionManager::get_singleton()->load_extension(config_file_path);
  842. ERR_CONTINUE_MSG(err == GDExtensionManager::LOAD_STATUS_FAILED, "Error loading platform extension: " + config_file_path);
  843. }
  844. }
  845. OS_Android::~OS_Android() {
  846. }