1/**************************************************************************/
2/* os.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
31#include "os.h"
32
33#include "core/config/project_settings.h"
34#include "core/input/input.h"
35#include "core/io/dir_access.h"
36#include "core/io/file_access.h"
37#include "core/io/json.h"
38#include "core/os/midi_driver.h"
39#include "core/version_generated.gen.h"
40
41#include <stdarg.h>
42#include <thread>
43
44OS *OS::singleton = nullptr;
45uint64_t OS::target_ticks = 0;
46
47OS *OS::get_singleton() {
48 return singleton;
49}
50
51uint64_t OS::get_ticks_msec() const {
52 return get_ticks_usec() / 1000ULL;
53}
54
55double OS::get_unix_time() const {
56 return 0;
57}
58
59void OS::_set_logger(CompositeLogger *p_logger) {
60 if (_logger) {
61 memdelete(_logger);
62 }
63 _logger = p_logger;
64}
65
66void OS::add_logger(Logger *p_logger) {
67 if (!_logger) {
68 Vector<Logger *> loggers;
69 loggers.push_back(p_logger);
70 _logger = memnew(CompositeLogger(loggers));
71 } else {
72 _logger->add_logger(p_logger);
73 }
74}
75
76String OS::get_identifier() const {
77 return get_name().to_lower();
78}
79
80void 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) {
81 if (!_stderr_enabled) {
82 return;
83 }
84
85 if (_logger) {
86 _logger->log_error(p_function, p_file, p_line, p_code, p_rationale, p_editor_notify, p_type);
87 }
88}
89
90void OS::print(const char *p_format, ...) {
91 if (!_stdout_enabled) {
92 return;
93 }
94
95 va_list argp;
96 va_start(argp, p_format);
97
98 if (_logger) {
99 _logger->logv(p_format, argp, false);
100 }
101
102 va_end(argp);
103}
104
105void OS::print_rich(const char *p_format, ...) {
106 if (!_stdout_enabled) {
107 return;
108 }
109
110 va_list argp;
111 va_start(argp, p_format);
112
113 if (_logger) {
114 _logger->logv(p_format, argp, false);
115 }
116
117 va_end(argp);
118}
119
120void OS::printerr(const char *p_format, ...) {
121 if (!_stderr_enabled) {
122 return;
123 }
124
125 va_list argp;
126 va_start(argp, p_format);
127
128 if (_logger) {
129 _logger->logv(p_format, argp, true);
130 }
131
132 va_end(argp);
133}
134
135void OS::alert(const String &p_alert, const String &p_title) {
136 fprintf(stderr, "%s: %s\n", p_title.utf8().get_data(), p_alert.utf8().get_data());
137}
138
139void OS::set_low_processor_usage_mode(bool p_enabled) {
140 low_processor_usage_mode = p_enabled;
141}
142
143bool OS::is_in_low_processor_usage_mode() const {
144 return low_processor_usage_mode;
145}
146
147void OS::set_low_processor_usage_mode_sleep_usec(int p_usec) {
148 low_processor_usage_mode_sleep_usec = p_usec;
149}
150
151int OS::get_low_processor_usage_mode_sleep_usec() const {
152 return low_processor_usage_mode_sleep_usec;
153}
154
155void OS::set_delta_smoothing(bool p_enabled) {
156 _delta_smoothing_enabled = p_enabled;
157}
158
159bool OS::is_delta_smoothing_enabled() const {
160 return _delta_smoothing_enabled;
161}
162
163String OS::get_executable_path() const {
164 return _execpath;
165}
166
167int OS::get_process_id() const {
168 return -1;
169}
170
171bool OS::is_stdout_verbose() const {
172 return _verbose_stdout;
173}
174
175bool OS::is_stdout_debug_enabled() const {
176 return _debug_stdout;
177}
178
179bool OS::is_stdout_enabled() const {
180 return _stdout_enabled;
181}
182
183bool OS::is_stderr_enabled() const {
184 return _stderr_enabled;
185}
186
187void OS::set_stdout_enabled(bool p_enabled) {
188 _stdout_enabled = p_enabled;
189}
190
191void OS::set_stderr_enabled(bool p_enabled) {
192 _stderr_enabled = p_enabled;
193}
194
195int OS::get_exit_code() const {
196 return _exit_code;
197}
198
199void OS::set_exit_code(int p_code) {
200 _exit_code = p_code;
201}
202
203String OS::get_locale() const {
204 return "en";
205}
206
207// Non-virtual helper to extract the 2 or 3-letter language code from
208// `get_locale()` in a way that's consistent for all platforms.
209String OS::get_locale_language() const {
210 return get_locale().left(3).replace("_", "");
211}
212
213// Embedded PCK offset.
214uint64_t OS::get_embedded_pck_offset() const {
215 return 0;
216}
217
218// Helper function to ensure that a dir name/path will be valid on the OS
219String OS::get_safe_dir_name(const String &p_dir_name, bool p_allow_paths) const {
220 String safe_dir_name = p_dir_name;
221 Vector<String> invalid_chars = String(": * ? \" < > |").split(" ");
222 if (p_allow_paths) {
223 // Dir separators are allowed, but disallow ".." to avoid going up the filesystem
224 invalid_chars.push_back("..");
225 safe_dir_name = safe_dir_name.replace("\\", "/").strip_edges();
226 } else {
227 invalid_chars.push_back("/");
228 invalid_chars.push_back("\\");
229 safe_dir_name = safe_dir_name.strip_edges();
230
231 // These directory names are invalid.
232 if (safe_dir_name == ".") {
233 safe_dir_name = "dot";
234 } else if (safe_dir_name == "..") {
235 safe_dir_name = "twodots";
236 }
237 }
238
239 for (int i = 0; i < invalid_chars.size(); i++) {
240 safe_dir_name = safe_dir_name.replace(invalid_chars[i], "-");
241 }
242 return safe_dir_name;
243}
244
245// Path to data, config, cache, etc. OS-specific folders
246
247// Get properly capitalized engine name for system paths
248String OS::get_godot_dir_name() const {
249 // Default to lowercase, so only override when different case is needed
250 return String(VERSION_SHORT_NAME).to_lower();
251}
252
253// OS equivalent of XDG_DATA_HOME
254String OS::get_data_path() const {
255 return ".";
256}
257
258// OS equivalent of XDG_CONFIG_HOME
259String OS::get_config_path() const {
260 return ".";
261}
262
263// OS equivalent of XDG_CACHE_HOME
264String OS::get_cache_path() const {
265 return ".";
266}
267
268// Path to macOS .app bundle resources
269String OS::get_bundle_resource_dir() const {
270 return ".";
271}
272
273// Path to macOS .app bundle embedded icon
274String OS::get_bundle_icon_path() const {
275 return String();
276}
277
278// OS specific path for user://
279String OS::get_user_data_dir() const {
280 return ".";
281}
282
283// Absolute path to res://
284String OS::get_resource_dir() const {
285 return ProjectSettings::get_singleton()->get_resource_path();
286}
287
288// Access system-specific dirs like Documents, Downloads, etc.
289String OS::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
290 return ".";
291}
292
293Error OS::shell_open(String p_uri) {
294 return ERR_UNAVAILABLE;
295}
296
297Error OS::shell_show_in_file_manager(String p_path, bool p_open_folder) {
298 p_path = p_path.trim_prefix("file://");
299
300 if (!DirAccess::dir_exists_absolute(p_path)) {
301 p_path = p_path.get_base_dir();
302 }
303
304 p_path = String("file://") + p_path;
305
306 return shell_open(p_path);
307}
308// implement these with the canvas?
309
310uint64_t OS::get_static_memory_usage() const {
311 return Memory::get_mem_usage();
312}
313
314uint64_t OS::get_static_memory_peak_usage() const {
315 return Memory::get_mem_max_usage();
316}
317
318Error OS::set_cwd(const String &p_cwd) {
319 return ERR_CANT_OPEN;
320}
321
322Dictionary OS::get_memory_info() const {
323 Dictionary meminfo;
324
325 meminfo["physical"] = -1;
326 meminfo["free"] = -1;
327 meminfo["available"] = -1;
328 meminfo["stack"] = -1;
329
330 return meminfo;
331}
332
333void OS::yield() {
334}
335
336void OS::ensure_user_data_dir() {
337 String dd = get_user_data_dir();
338 if (DirAccess::exists(dd)) {
339 return;
340 }
341
342 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
343 Error err = da->make_dir_recursive(dd);
344 ERR_FAIL_COND_MSG(err != OK, "Error attempting to create data dir: " + dd + ".");
345}
346
347String OS::get_model_name() const {
348 return "GenericDevice";
349}
350
351void OS::set_cmdline(const char *p_execpath, const List<String> &p_args, const List<String> &p_user_args) {
352 _execpath = String::utf8(p_execpath);
353 _cmdline = p_args;
354 _user_args = p_user_args;
355}
356
357String OS::get_unique_id() const {
358 ERR_FAIL_V("");
359}
360
361int OS::get_processor_count() const {
362 return std::thread::hardware_concurrency();
363}
364
365String OS::get_processor_name() const {
366 return "";
367}
368
369void OS::set_has_server_feature_callback(HasServerFeatureCallback p_callback) {
370 has_server_feature_callback = p_callback;
371}
372
373bool OS::has_feature(const String &p_feature) {
374 // Feature tags are always lowercase for consistency.
375 if (p_feature == get_identifier()) {
376 return true;
377 }
378
379 if (p_feature == "movie") {
380 return _writing_movie;
381 }
382
383#ifdef DEBUG_ENABLED
384 if (p_feature == "debug") {
385 return true;
386 }
387#endif // DEBUG_ENABLED
388
389#ifdef TOOLS_ENABLED
390 if (p_feature == "editor") {
391 return true;
392 }
393#else
394 if (p_feature == "template") {
395 return true;
396 }
397#ifdef DEBUG_ENABLED
398 if (p_feature == "template_debug") {
399 return true;
400 }
401#else
402 if (p_feature == "template_release" || p_feature == "release") {
403 return true;
404 }
405#endif // DEBUG_ENABLED
406#endif // TOOLS_ENABLED
407
408#ifdef REAL_T_IS_DOUBLE
409 if (p_feature == "double") {
410 return true;
411 }
412#else
413 if (p_feature == "single") {
414 return true;
415 }
416#endif // REAL_T_IS_DOUBLE
417
418 if (sizeof(void *) == 8 && p_feature == "64") {
419 return true;
420 }
421 if (sizeof(void *) == 4 && p_feature == "32") {
422 return true;
423 }
424#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(_M_X64)
425#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(_M_X64)
426 if (p_feature == "x86_64") {
427 return true;
428 }
429#elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
430 if (p_feature == "x86_32") {
431 return true;
432 }
433#endif
434 if (p_feature == "x86") {
435 return true;
436 }
437#elif defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
438#if defined(__aarch64__) || defined(_M_ARM64)
439 if (p_feature == "arm64") {
440 return true;
441 }
442#elif defined(__arm__) || defined(_M_ARM)
443 if (p_feature == "arm32") {
444 return true;
445 }
446#endif
447#if defined(__ARM_ARCH_7A__)
448 if (p_feature == "armv7a" || p_feature == "armv7") {
449 return true;
450 }
451#endif
452#if defined(__ARM_ARCH_7S__)
453 if (p_feature == "armv7s" || p_feature == "armv7") {
454 return true;
455 }
456#endif
457 if (p_feature == "arm") {
458 return true;
459 }
460#elif defined(__riscv)
461#if __riscv_xlen == 8
462 if (p_feature == "rv64") {
463 return true;
464 }
465#endif
466 if (p_feature == "riscv") {
467 return true;
468 }
469#elif defined(__powerpc__)
470#if defined(__powerpc64__)
471 if (p_feature == "ppc64") {
472 return true;
473 }
474#endif
475 if (p_feature == "ppc") {
476 return true;
477 }
478#elif defined(__wasm__)
479#if defined(__wasm64__)
480 if (p_feature == "wasm64") {
481 return true;
482 }
483#elif defined(__wasm32__)
484 if (p_feature == "wasm32") {
485 return true;
486 }
487#endif
488 if (p_feature == "wasm") {
489 return true;
490 }
491#endif
492
493 if (_check_internal_feature_support(p_feature)) {
494 return true;
495 }
496
497 if (has_server_feature_callback && has_server_feature_callback(p_feature)) {
498 return true;
499 }
500
501 if (ProjectSettings::get_singleton()->has_custom_feature(p_feature)) {
502 return true;
503 }
504
505 return false;
506}
507
508bool OS::is_sandboxed() const {
509 return false;
510}
511
512void OS::set_restart_on_exit(bool p_restart, const List<String> &p_restart_arguments) {
513 restart_on_exit = p_restart;
514 restart_commandline = p_restart_arguments;
515}
516
517bool OS::is_restart_on_exit_set() const {
518 return restart_on_exit;
519}
520
521List<String> OS::get_restart_on_exit_arguments() const {
522 return restart_commandline;
523}
524
525PackedStringArray OS::get_connected_midi_inputs() {
526 if (MIDIDriver::get_singleton()) {
527 return MIDIDriver::get_singleton()->get_connected_inputs();
528 }
529
530 PackedStringArray list;
531 ERR_FAIL_V_MSG(list, vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
532}
533
534void OS::open_midi_inputs() {
535 if (MIDIDriver::get_singleton()) {
536 MIDIDriver::get_singleton()->open();
537 } else {
538 ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
539 }
540}
541
542void OS::close_midi_inputs() {
543 if (MIDIDriver::get_singleton()) {
544 MIDIDriver::get_singleton()->close();
545 } else {
546 ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
547 }
548}
549
550void OS::add_frame_delay(bool p_can_draw) {
551 const uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
552 if (frame_delay) {
553 // Add fixed frame delay to decrease CPU/GPU usage. This doesn't take
554 // the actual frame time into account.
555 // Due to the high fluctuation of the actual sleep duration, it's not recommended
556 // to use this as a FPS limiter.
557 delay_usec(frame_delay * 1000);
558 }
559
560 // Add a dynamic frame delay to decrease CPU/GPU usage. This takes the
561 // previous frame time into account for a smoother result.
562 uint64_t dynamic_delay = 0;
563 if (is_in_low_processor_usage_mode() || !p_can_draw) {
564 dynamic_delay = get_low_processor_usage_mode_sleep_usec();
565 }
566 const int max_fps = Engine::get_singleton()->get_max_fps();
567 if (max_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
568 // Override the low processor usage mode sleep delay if the target FPS is lower.
569 dynamic_delay = MAX(dynamic_delay, (uint64_t)(1000000 / max_fps));
570 }
571
572 if (dynamic_delay > 0) {
573 target_ticks += dynamic_delay;
574 uint64_t current_ticks = get_ticks_usec();
575
576 if (current_ticks < target_ticks) {
577 delay_usec(target_ticks - current_ticks);
578 }
579
580 current_ticks = get_ticks_usec();
581 target_ticks = MIN(MAX(target_ticks, current_ticks - dynamic_delay), current_ticks + dynamic_delay);
582 }
583}
584
585Error OS::setup_remote_filesystem(const String &p_server_host, int p_port, const String &p_password, String &r_project_path) {
586 return default_rfs.synchronize_with_server(p_server_host, p_port, p_password, r_project_path);
587}
588
589OS::PreferredTextureFormat OS::get_preferred_texture_format() const {
590#if defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
591 return PREFERRED_TEXTURE_FORMAT_ETC2_ASTC; // By rule, ARM hardware uses ETC texture compression.
592#elif defined(__x86_64__) || defined(_M_X64) || defined(i386) || defined(__i386__) || defined(__i386) || defined(_M_IX86)
593 return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC; // By rule, X86 hardware prefers S3TC and derivatives.
594#else
595 return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC; // Override in platform if needed.
596#endif
597}
598
599void OS::set_use_benchmark(bool p_use_benchmark) {
600 use_benchmark = p_use_benchmark;
601}
602
603bool OS::is_use_benchmark_set() {
604 return use_benchmark;
605}
606
607void OS::set_benchmark_file(const String &p_benchmark_file) {
608 benchmark_file = p_benchmark_file;
609}
610
611String OS::get_benchmark_file() {
612 return benchmark_file;
613}
614
615void OS::benchmark_begin_measure(const String &p_what) {
616#ifdef TOOLS_ENABLED
617 start_benchmark_from[p_what] = OS::get_singleton()->get_ticks_usec();
618#endif
619}
620void OS::benchmark_end_measure(const String &p_what) {
621#ifdef TOOLS_ENABLED
622 uint64_t total = OS::get_singleton()->get_ticks_usec() - start_benchmark_from[p_what];
623 double total_f = double(total) / double(1000000);
624
625 startup_benchmark_json[p_what] = total_f;
626#endif
627}
628
629void OS::benchmark_dump() {
630#ifdef TOOLS_ENABLED
631 if (!use_benchmark) {
632 return;
633 }
634 if (!benchmark_file.is_empty()) {
635 Ref<FileAccess> f = FileAccess::open(benchmark_file, FileAccess::WRITE);
636 if (f.is_valid()) {
637 Ref<JSON> json;
638 json.instantiate();
639 f->store_string(json->stringify(startup_benchmark_json, "\t", false, true));
640 }
641 } else {
642 List<Variant> keys;
643 startup_benchmark_json.get_key_list(&keys);
644 print_line("BENCHMARK:");
645 for (const Variant &K : keys) {
646 print_line("\t-", K, ": ", startup_benchmark_json[K], +" sec.");
647 }
648 }
649#endif
650}
651
652OS::OS() {
653 singleton = this;
654
655 Vector<Logger *> loggers;
656 loggers.push_back(memnew(StdLogger));
657 _set_logger(memnew(CompositeLogger(loggers)));
658}
659
660OS::~OS() {
661 if (_logger) {
662 memdelete(_logger);
663 }
664 singleton = nullptr;
665}
666