os.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /*************************************************************************/
  2. /* os.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "os.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/input/input.h"
  33. #include "core/io/dir_access.h"
  34. #include "core/io/file_access.h"
  35. #include "core/os/midi_driver.h"
  36. #include "core/version_generated.gen.h"
  37. #include <stdarg.h>
  38. OS *OS::singleton = nullptr;
  39. uint64_t OS::target_ticks = 0;
  40. OS *OS::get_singleton() {
  41. return singleton;
  42. }
  43. uint64_t OS::get_ticks_msec() const {
  44. return get_ticks_usec() / 1000ULL;
  45. }
  46. double OS::get_unix_time() const {
  47. return 0;
  48. }
  49. void OS::debug_break() {
  50. // something
  51. }
  52. void OS::_set_logger(CompositeLogger *p_logger) {
  53. if (_logger) {
  54. memdelete(_logger);
  55. }
  56. _logger = p_logger;
  57. }
  58. void OS::add_logger(Logger *p_logger) {
  59. if (!_logger) {
  60. Vector<Logger *> loggers;
  61. loggers.push_back(p_logger);
  62. _logger = memnew(CompositeLogger(loggers));
  63. } else {
  64. _logger->add_logger(p_logger);
  65. }
  66. }
  67. void OS::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify, Logger::ErrorType p_type) {
  68. if (!_stderr_enabled) {
  69. return;
  70. }
  71. _logger->log_error(p_function, p_file, p_line, p_code, p_rationale, p_editor_notify, p_type);
  72. }
  73. void OS::print(const char *p_format, ...) {
  74. if (!_stdout_enabled) {
  75. return;
  76. }
  77. va_list argp;
  78. va_start(argp, p_format);
  79. _logger->logv(p_format, argp, false);
  80. va_end(argp);
  81. }
  82. void OS::printerr(const char *p_format, ...) {
  83. if (!_stderr_enabled) {
  84. return;
  85. }
  86. va_list argp;
  87. va_start(argp, p_format);
  88. _logger->logv(p_format, argp, true);
  89. va_end(argp);
  90. }
  91. void OS::alert(const String &p_alert, const String &p_title) {
  92. fprintf(stderr, "%s: %s\n", p_title.utf8().get_data(), p_alert.utf8().get_data());
  93. }
  94. void OS::set_low_processor_usage_mode(bool p_enabled) {
  95. low_processor_usage_mode = p_enabled;
  96. }
  97. bool OS::is_in_low_processor_usage_mode() const {
  98. return low_processor_usage_mode;
  99. }
  100. void OS::set_low_processor_usage_mode_sleep_usec(int p_usec) {
  101. low_processor_usage_mode_sleep_usec = p_usec;
  102. }
  103. int OS::get_low_processor_usage_mode_sleep_usec() const {
  104. return low_processor_usage_mode_sleep_usec;
  105. }
  106. String OS::get_executable_path() const {
  107. return _execpath;
  108. }
  109. int OS::get_process_id() const {
  110. return -1;
  111. }
  112. void OS::vibrate_handheld(int p_duration_ms) {
  113. WARN_PRINT("vibrate_handheld() only works with Android and iOS");
  114. }
  115. bool OS::is_stdout_verbose() const {
  116. return _verbose_stdout;
  117. }
  118. bool OS::is_single_window() const {
  119. return _single_window;
  120. }
  121. bool OS::is_stdout_debug_enabled() const {
  122. return _debug_stdout;
  123. }
  124. bool OS::is_stdout_enabled() const {
  125. return _stdout_enabled;
  126. }
  127. bool OS::is_stderr_enabled() const {
  128. return _stderr_enabled;
  129. }
  130. void OS::set_stdout_enabled(bool p_enabled) {
  131. _stdout_enabled = p_enabled;
  132. }
  133. void OS::set_stderr_enabled(bool p_enabled) {
  134. _stderr_enabled = p_enabled;
  135. }
  136. void OS::dump_memory_to_file(const char *p_file) {
  137. //Memory::dump_static_mem_to_file(p_file);
  138. }
  139. static FileAccess *_OSPRF = nullptr;
  140. static void _OS_printres(Object *p_obj) {
  141. Resource *res = Object::cast_to<Resource>(p_obj);
  142. if (!res) {
  143. return;
  144. }
  145. String str = vformat("%s - %s - %s", res->to_string(), res->get_name(), res->get_path());
  146. if (_OSPRF) {
  147. _OSPRF->store_line(str);
  148. } else {
  149. print_line(str);
  150. }
  151. }
  152. void OS::print_all_resources(String p_to_file) {
  153. ERR_FAIL_COND(p_to_file != "" && _OSPRF);
  154. if (p_to_file != "") {
  155. Error err;
  156. _OSPRF = FileAccess::open(p_to_file, FileAccess::WRITE, &err);
  157. if (err != OK) {
  158. _OSPRF = nullptr;
  159. ERR_FAIL_MSG("Can't print all resources to file: " + String(p_to_file) + ".");
  160. }
  161. }
  162. ObjectDB::debug_objects(_OS_printres);
  163. if (p_to_file != "") {
  164. if (_OSPRF) {
  165. memdelete(_OSPRF);
  166. }
  167. _OSPRF = nullptr;
  168. }
  169. }
  170. void OS::print_resources_in_use(bool p_short) {
  171. ResourceCache::dump(nullptr, p_short);
  172. }
  173. void OS::dump_resources_to_file(const char *p_file) {
  174. ResourceCache::dump(p_file);
  175. }
  176. int OS::get_exit_code() const {
  177. return _exit_code;
  178. }
  179. void OS::set_exit_code(int p_code) {
  180. _exit_code = p_code;
  181. }
  182. String OS::get_locale() const {
  183. return "en";
  184. }
  185. // Non-virtual helper to extract the 2 or 3-letter language code from
  186. // `get_locale()` in a way that's consistent for all platforms.
  187. String OS::get_locale_language() const {
  188. return get_locale().left(3).replace("_", "");
  189. }
  190. // Helper function to ensure that a dir name/path will be valid on the OS
  191. String OS::get_safe_dir_name(const String &p_dir_name, bool p_allow_dir_separator) const {
  192. Vector<String> invalid_chars = String(": * ? \" < > |").split(" ");
  193. if (p_allow_dir_separator) {
  194. // Dir separators are allowed, but disallow ".." to avoid going up the filesystem
  195. invalid_chars.push_back("..");
  196. } else {
  197. invalid_chars.push_back("/");
  198. }
  199. String safe_dir_name = p_dir_name.replace("\\", "/").strip_edges();
  200. for (int i = 0; i < invalid_chars.size(); i++) {
  201. safe_dir_name = safe_dir_name.replace(invalid_chars[i], "-");
  202. }
  203. return safe_dir_name;
  204. }
  205. // Path to data, config, cache, etc. OS-specific folders
  206. // Get properly capitalized engine name for system paths
  207. String OS::get_godot_dir_name() const {
  208. // Default to lowercase, so only override when different case is needed
  209. return String(VERSION_SHORT_NAME).to_lower();
  210. }
  211. // OS equivalent of XDG_DATA_HOME
  212. String OS::get_data_path() const {
  213. return ".";
  214. }
  215. // OS equivalent of XDG_CONFIG_HOME
  216. String OS::get_config_path() const {
  217. return ".";
  218. }
  219. // OS equivalent of XDG_CACHE_HOME
  220. String OS::get_cache_path() const {
  221. return ".";
  222. }
  223. // Path to macOS .app bundle resources
  224. String OS::get_bundle_resource_dir() const {
  225. return ".";
  226. }
  227. // Path to macOS .app bundle embedded icon
  228. String OS::get_bundle_icon_path() const {
  229. return String();
  230. }
  231. // OS specific path for user://
  232. String OS::get_user_data_dir() const {
  233. return ".";
  234. }
  235. // Absolute path to res://
  236. String OS::get_resource_dir() const {
  237. return ProjectSettings::get_singleton()->get_resource_path();
  238. }
  239. // Access system-specific dirs like Documents, Downloads, etc.
  240. String OS::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  241. return ".";
  242. }
  243. Error OS::shell_open(String p_uri) {
  244. return ERR_UNAVAILABLE;
  245. }
  246. // implement these with the canvas?
  247. uint64_t OS::get_static_memory_usage() const {
  248. return Memory::get_mem_usage();
  249. }
  250. uint64_t OS::get_static_memory_peak_usage() const {
  251. return Memory::get_mem_max_usage();
  252. }
  253. Error OS::set_cwd(const String &p_cwd) {
  254. return ERR_CANT_OPEN;
  255. }
  256. uint64_t OS::get_free_static_memory() const {
  257. return Memory::get_mem_available();
  258. }
  259. void OS::yield() {
  260. }
  261. void OS::ensure_user_data_dir() {
  262. String dd = get_user_data_dir();
  263. DirAccess *da = DirAccess::open(dd);
  264. if (da) {
  265. memdelete(da);
  266. return;
  267. }
  268. da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  269. Error err = da->make_dir_recursive(dd);
  270. ERR_FAIL_COND_MSG(err != OK, "Error attempting to create data dir: " + dd + ".");
  271. memdelete(da);
  272. }
  273. String OS::get_model_name() const {
  274. return "GenericDevice";
  275. }
  276. void OS::set_cmdline(const char *p_execpath, const List<String> &p_args) {
  277. _execpath = p_execpath;
  278. _cmdline = p_args;
  279. }
  280. String OS::get_unique_id() const {
  281. ERR_FAIL_V("");
  282. }
  283. int OS::get_processor_count() const {
  284. return 1;
  285. }
  286. bool OS::can_use_threads() const {
  287. #ifdef NO_THREADS
  288. return false;
  289. #else
  290. return true;
  291. #endif
  292. }
  293. void OS::set_has_server_feature_callback(HasServerFeatureCallback p_callback) {
  294. has_server_feature_callback = p_callback;
  295. }
  296. bool OS::has_feature(const String &p_feature) {
  297. // Feature tags are always lowercase for consistency.
  298. if (p_feature == get_name().to_lower()) {
  299. return true;
  300. }
  301. // Catch-all `linuxbsd` feature tag that matches on both Linux and BSD.
  302. // This is the one exposed in the project settings dialog.
  303. if (p_feature == "linuxbsd" && (get_name() == "Linux" || get_name() == "FreeBSD" || get_name() == "NetBSD" || get_name() == "OpenBSD" || get_name() == "BSD")) {
  304. return true;
  305. }
  306. #ifdef DEBUG_ENABLED
  307. if (p_feature == "debug") {
  308. return true;
  309. }
  310. #else
  311. if (p_feature == "release")
  312. return true;
  313. #endif
  314. #ifdef TOOLS_ENABLED
  315. if (p_feature == "editor") {
  316. return true;
  317. }
  318. #else
  319. if (p_feature == "standalone")
  320. return true;
  321. #endif
  322. if (sizeof(void *) == 8 && p_feature == "64") {
  323. return true;
  324. }
  325. if (sizeof(void *) == 4 && p_feature == "32") {
  326. return true;
  327. }
  328. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__)
  329. if (p_feature == "x86_64") {
  330. return true;
  331. }
  332. #elif (defined(__i386) || defined(__i386__))
  333. if (p_feature == "x86") {
  334. return true;
  335. }
  336. #elif defined(__aarch64__)
  337. if (p_feature == "arm64") {
  338. return true;
  339. }
  340. #elif defined(__arm__)
  341. #if defined(__ARM_ARCH_7A__)
  342. if (p_feature == "armv7a" || p_feature == "armv7") {
  343. return true;
  344. }
  345. #endif
  346. #if defined(__ARM_ARCH_7S__)
  347. if (p_feature == "armv7s" || p_feature == "armv7") {
  348. return true;
  349. }
  350. #endif
  351. if (p_feature == "arm") {
  352. return true;
  353. }
  354. #elif defined(__riscv)
  355. #if __riscv_xlen == 8
  356. if (p_feature == "rv64") {
  357. return true;
  358. }
  359. #endif
  360. if (p_feature == "riscv") {
  361. return true;
  362. }
  363. #elif defined(__powerpc__)
  364. #if defined(__powerpc64__)
  365. if (p_feature == "ppc64") {
  366. return true;
  367. }
  368. #endif
  369. if (p_feature == "ppc") {
  370. return true;
  371. }
  372. #endif
  373. if (_check_internal_feature_support(p_feature)) {
  374. return true;
  375. }
  376. if (has_server_feature_callback && has_server_feature_callback(p_feature)) {
  377. return true;
  378. }
  379. if (ProjectSettings::get_singleton()->has_custom_feature(p_feature)) {
  380. return true;
  381. }
  382. return false;
  383. }
  384. void OS::set_restart_on_exit(bool p_restart, const List<String> &p_restart_arguments) {
  385. restart_on_exit = p_restart;
  386. restart_commandline = p_restart_arguments;
  387. }
  388. bool OS::is_restart_on_exit_set() const {
  389. return restart_on_exit;
  390. }
  391. List<String> OS::get_restart_on_exit_arguments() const {
  392. return restart_commandline;
  393. }
  394. PackedStringArray OS::get_connected_midi_inputs() {
  395. if (MIDIDriver::get_singleton()) {
  396. return MIDIDriver::get_singleton()->get_connected_inputs();
  397. }
  398. PackedStringArray list;
  399. ERR_FAIL_V_MSG(list, vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  400. }
  401. void OS::open_midi_inputs() {
  402. if (MIDIDriver::get_singleton()) {
  403. MIDIDriver::get_singleton()->open();
  404. } else {
  405. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  406. }
  407. }
  408. void OS::close_midi_inputs() {
  409. if (MIDIDriver::get_singleton()) {
  410. MIDIDriver::get_singleton()->close();
  411. } else {
  412. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  413. }
  414. }
  415. void OS::add_frame_delay(bool p_can_draw) {
  416. const uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
  417. if (frame_delay) {
  418. // Add fixed frame delay to decrease CPU/GPU usage. This doesn't take
  419. // the actual frame time into account.
  420. // Due to the high fluctuation of the actual sleep duration, it's not recommended
  421. // to use this as a FPS limiter.
  422. delay_usec(frame_delay * 1000);
  423. }
  424. // Add a dynamic frame delay to decrease CPU/GPU usage. This takes the
  425. // previous frame time into account for a smoother result.
  426. uint64_t dynamic_delay = 0;
  427. if (is_in_low_processor_usage_mode() || !p_can_draw) {
  428. dynamic_delay = get_low_processor_usage_mode_sleep_usec();
  429. }
  430. const int target_fps = Engine::get_singleton()->get_target_fps();
  431. if (target_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
  432. // Override the low processor usage mode sleep delay if the target FPS is lower.
  433. dynamic_delay = MAX(dynamic_delay, (uint64_t)(1000000 / target_fps));
  434. }
  435. if (dynamic_delay > 0) {
  436. target_ticks += dynamic_delay;
  437. uint64_t current_ticks = get_ticks_usec();
  438. if (current_ticks < target_ticks) {
  439. delay_usec(target_ticks - current_ticks);
  440. }
  441. current_ticks = get_ticks_usec();
  442. target_ticks = MIN(MAX(target_ticks, current_ticks - dynamic_delay), current_ticks + dynamic_delay);
  443. }
  444. }
  445. OS::OS() {
  446. singleton = this;
  447. Vector<Logger *> loggers;
  448. loggers.push_back(memnew(StdLogger));
  449. _set_logger(memnew(CompositeLogger(loggers)));
  450. }
  451. OS::~OS() {
  452. memdelete(_logger);
  453. singleton = nullptr;
  454. }