1 /*************************************************************************/
2 /*  os.cpp                                                               */
3 /*************************************************************************/
4 /*                       This file is part of:                           */
5 /*                           GODOT ENGINE                                */
6 /*                      https://godotengine.org                          */
7 /*************************************************************************/
8 /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
9 /* Copyright (c) 2014-2020 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 
31 #include "os.h"
32 
33 #include "core/os/dir_access.h"
34 #include "core/os/file_access.h"
35 #include "core/os/input.h"
36 #include "core/os/midi_driver.h"
37 #include "core/project_settings.h"
38 #include "core/version_generated.gen.h"
39 #include "servers/audio_server.h"
40 
41 #include <stdarg.h>
42 
43 OS *OS::singleton = NULL;
44 uint64_t OS::target_ticks = 0;
45 
get_singleton()46 OS *OS::get_singleton() {
47 
48 	return singleton;
49 }
50 
get_ticks_msec() const51 uint32_t OS::get_ticks_msec() const {
52 	return get_ticks_usec() / 1000;
53 }
54 
get_iso_date_time(bool local) const55 String OS::get_iso_date_time(bool local) const {
56 	OS::Date date = get_date(local);
57 	OS::Time time = get_time(local);
58 
59 	String timezone;
60 	if (!local) {
61 		TimeZoneInfo zone = get_time_zone_info();
62 		if (zone.bias >= 0) {
63 			timezone = "+";
64 		}
65 		timezone = timezone + itos(zone.bias / 60).pad_zeros(2) + itos(zone.bias % 60).pad_zeros(2);
66 	} else {
67 		timezone = "Z";
68 	}
69 
70 	return itos(date.year).pad_zeros(2) +
71 		   "-" +
72 		   itos(date.month).pad_zeros(2) +
73 		   "-" +
74 		   itos(date.day).pad_zeros(2) +
75 		   "T" +
76 		   itos(time.hour).pad_zeros(2) +
77 		   ":" +
78 		   itos(time.min).pad_zeros(2) +
79 		   ":" +
80 		   itos(time.sec).pad_zeros(2) +
81 		   timezone;
82 }
83 
get_splash_tick_msec() const84 uint64_t OS::get_splash_tick_msec() const {
85 	return _msec_splash;
86 }
get_unix_time() const87 uint64_t OS::get_unix_time() const {
88 
89 	return 0;
90 };
get_system_time_secs() const91 uint64_t OS::get_system_time_secs() const {
92 	return 0;
93 }
get_system_time_msecs() const94 uint64_t OS::get_system_time_msecs() const {
95 	return 0;
96 }
debug_break()97 void OS::debug_break(){
98 
99 	// something
100 };
101 
_set_logger(CompositeLogger * p_logger)102 void OS::_set_logger(CompositeLogger *p_logger) {
103 	if (_logger) {
104 		memdelete(_logger);
105 	}
106 	_logger = p_logger;
107 }
108 
add_logger(Logger * p_logger)109 void OS::add_logger(Logger *p_logger) {
110 	if (!_logger) {
111 		Vector<Logger *> loggers;
112 		loggers.push_back(p_logger);
113 		_logger = memnew(CompositeLogger(loggers));
114 	} else {
115 		_logger->add_logger(p_logger);
116 	}
117 }
118 
print_error(const char * p_function,const char * p_file,int p_line,const char * p_code,const char * p_rationale,Logger::ErrorType p_type)119 void OS::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, Logger::ErrorType p_type) {
120 
121 	_logger->log_error(p_function, p_file, p_line, p_code, p_rationale, p_type);
122 }
123 
print(const char * p_format,...)124 void OS::print(const char *p_format, ...) {
125 
126 	va_list argp;
127 	va_start(argp, p_format);
128 
129 	_logger->logv(p_format, argp, false);
130 
131 	va_end(argp);
132 };
133 
printerr(const char * p_format,...)134 void OS::printerr(const char *p_format, ...) {
135 	va_list argp;
136 	va_start(argp, p_format);
137 
138 	_logger->logv(p_format, argp, true);
139 
140 	va_end(argp);
141 };
142 
set_keep_screen_on(bool p_enabled)143 void OS::set_keep_screen_on(bool p_enabled) {
144 	_keep_screen_on = p_enabled;
145 }
146 
is_keep_screen_on() const147 bool OS::is_keep_screen_on() const {
148 	return _keep_screen_on;
149 }
150 
set_low_processor_usage_mode(bool p_enabled)151 void OS::set_low_processor_usage_mode(bool p_enabled) {
152 
153 	low_processor_usage_mode = p_enabled;
154 }
155 
is_in_low_processor_usage_mode() const156 bool OS::is_in_low_processor_usage_mode() const {
157 
158 	return low_processor_usage_mode;
159 }
160 
set_low_processor_usage_mode_sleep_usec(int p_usec)161 void OS::set_low_processor_usage_mode_sleep_usec(int p_usec) {
162 
163 	low_processor_usage_mode_sleep_usec = p_usec;
164 }
165 
get_low_processor_usage_mode_sleep_usec() const166 int OS::get_low_processor_usage_mode_sleep_usec() const {
167 
168 	return low_processor_usage_mode_sleep_usec;
169 }
170 
set_clipboard(const String & p_text)171 void OS::set_clipboard(const String &p_text) {
172 
173 	_local_clipboard = p_text;
174 }
get_clipboard() const175 String OS::get_clipboard() const {
176 
177 	return _local_clipboard;
178 }
179 
get_executable_path() const180 String OS::get_executable_path() const {
181 
182 	return _execpath;
183 }
184 
get_process_id() const185 int OS::get_process_id() const {
186 
187 	return -1;
188 };
189 
vibrate_handheld(int p_duration_ms)190 void OS::vibrate_handheld(int p_duration_ms) {
191 
192 	WARN_PRINTS("vibrate_handheld() only works with Android and iOS");
193 }
194 
is_stdout_verbose() const195 bool OS::is_stdout_verbose() const {
196 
197 	return _verbose_stdout;
198 }
199 
is_stdout_debug_enabled() const200 bool OS::is_stdout_debug_enabled() const {
201 	return _debug_stdout;
202 }
203 
dump_memory_to_file(const char * p_file)204 void OS::dump_memory_to_file(const char *p_file) {
205 
206 	//Memory::dump_static_mem_to_file(p_file);
207 }
208 
209 static FileAccess *_OSPRF = NULL;
210 
_OS_printres(Object * p_obj)211 static void _OS_printres(Object *p_obj) {
212 
213 	Resource *res = Object::cast_to<Resource>(p_obj);
214 	if (!res)
215 		return;
216 
217 	String str = itos(res->get_instance_id()) + String(res->get_class()) + ":" + String(res->get_name()) + " - " + res->get_path();
218 	if (_OSPRF)
219 		_OSPRF->store_line(str);
220 	else
221 		print_line(str);
222 }
223 
has_virtual_keyboard() const224 bool OS::has_virtual_keyboard() const {
225 
226 	return false;
227 }
228 
show_virtual_keyboard(const String & p_existing_text,const Rect2 & p_screen_rect,bool p_multiline,int p_max_input_length,int p_cursor_start,int p_cursor_end)229 void OS::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect, bool p_multiline, int p_max_input_length, int p_cursor_start, int p_cursor_end) {
230 }
231 
hide_virtual_keyboard()232 void OS::hide_virtual_keyboard() {
233 }
234 
get_virtual_keyboard_height() const235 int OS::get_virtual_keyboard_height() const {
236 	return 0;
237 }
238 
set_cursor_shape(CursorShape p_shape)239 void OS::set_cursor_shape(CursorShape p_shape) {
240 }
241 
get_cursor_shape() const242 OS::CursorShape OS::get_cursor_shape() const {
243 	return CURSOR_ARROW;
244 }
245 
set_custom_mouse_cursor(const RES & p_cursor,CursorShape p_shape,const Vector2 & p_hotspot)246 void OS::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
247 }
248 
print_all_resources(String p_to_file)249 void OS::print_all_resources(String p_to_file) {
250 
251 	ERR_FAIL_COND(p_to_file != "" && _OSPRF);
252 	if (p_to_file != "") {
253 
254 		Error err;
255 		_OSPRF = FileAccess::open(p_to_file, FileAccess::WRITE, &err);
256 		if (err != OK) {
257 			_OSPRF = NULL;
258 			ERR_FAIL_MSG("Can't print all resources to file: " + String(p_to_file) + ".");
259 		}
260 	}
261 
262 	ObjectDB::debug_objects(_OS_printres);
263 
264 	if (p_to_file != "") {
265 
266 		if (_OSPRF)
267 			memdelete(_OSPRF);
268 		_OSPRF = NULL;
269 	}
270 }
271 
print_resources_in_use(bool p_short)272 void OS::print_resources_in_use(bool p_short) {
273 
274 	ResourceCache::dump(NULL, p_short);
275 }
276 
dump_resources_to_file(const char * p_file)277 void OS::dump_resources_to_file(const char *p_file) {
278 
279 	ResourceCache::dump(p_file);
280 }
281 
set_no_window_mode(bool p_enable)282 void OS::set_no_window_mode(bool p_enable) {
283 
284 	_no_window = p_enable;
285 }
286 
is_no_window_mode_enabled() const287 bool OS::is_no_window_mode_enabled() const {
288 
289 	return _no_window;
290 }
291 
get_exit_code() const292 int OS::get_exit_code() const {
293 
294 	return _exit_code;
295 }
set_exit_code(int p_code)296 void OS::set_exit_code(int p_code) {
297 
298 	_exit_code = p_code;
299 }
300 
get_locale() const301 String OS::get_locale() const {
302 
303 	return "en";
304 }
305 
306 // Helper function to ensure that a dir name/path will be valid on the OS
get_safe_dir_name(const String & p_dir_name,bool p_allow_dir_separator) const307 String OS::get_safe_dir_name(const String &p_dir_name, bool p_allow_dir_separator) const {
308 
309 	Vector<String> invalid_chars = String(": * ? \" < > |").split(" ");
310 	if (p_allow_dir_separator) {
311 		// Dir separators are allowed, but disallow ".." to avoid going up the filesystem
312 		invalid_chars.push_back("..");
313 	} else {
314 		invalid_chars.push_back("/");
315 	}
316 
317 	String safe_dir_name = p_dir_name.replace("\\", "/").strip_edges();
318 	for (int i = 0; i < invalid_chars.size(); i++) {
319 		safe_dir_name = safe_dir_name.replace(invalid_chars[i], "-");
320 	}
321 	return safe_dir_name;
322 }
323 
324 // Path to data, config, cache, etc. OS-specific folders
325 
326 // Get properly capitalized engine name for system paths
get_godot_dir_name() const327 String OS::get_godot_dir_name() const {
328 
329 	// Default to lowercase, so only override when different case is needed
330 	return String(VERSION_SHORT_NAME).to_lower();
331 }
332 
333 // OS equivalent of XDG_DATA_HOME
get_data_path() const334 String OS::get_data_path() const {
335 
336 	return ".";
337 }
338 
339 // OS equivalent of XDG_CONFIG_HOME
get_config_path() const340 String OS::get_config_path() const {
341 
342 	return ".";
343 }
344 
345 // OS equivalent of XDG_CACHE_HOME
get_cache_path() const346 String OS::get_cache_path() const {
347 
348 	return ".";
349 }
350 
351 // Path to macOS .app bundle resources
get_bundle_resource_dir() const352 String OS::get_bundle_resource_dir() const {
353 
354 	return ".";
355 };
356 
357 // OS specific path for user://
get_user_data_dir() const358 String OS::get_user_data_dir() const {
359 
360 	return ".";
361 };
362 
363 // Absolute path to res://
get_resource_dir() const364 String OS::get_resource_dir() const {
365 
366 	return ProjectSettings::get_singleton()->get_resource_path();
367 }
368 
369 // Access system-specific dirs like Documents, Downloads, etc.
get_system_dir(SystemDir p_dir) const370 String OS::get_system_dir(SystemDir p_dir) const {
371 
372 	return ".";
373 }
374 
shell_open(String p_uri)375 Error OS::shell_open(String p_uri) {
376 	return ERR_UNAVAILABLE;
377 };
378 
379 // implement these with the canvas?
dialog_show(String p_title,String p_description,Vector<String> p_buttons,Object * p_obj,String p_callback)380 Error OS::dialog_show(String p_title, String p_description, Vector<String> p_buttons, Object *p_obj, String p_callback) {
381 
382 	while (true) {
383 
384 		print("%ls\n--------\n%ls\n", p_title.c_str(), p_description.c_str());
385 		for (int i = 0; i < p_buttons.size(); i++) {
386 			if (i > 0) print(", ");
387 			print("%i=%ls", i + 1, p_buttons[i].c_str());
388 		};
389 		print("\n");
390 		String res = get_stdin_string().strip_edges();
391 		if (!res.is_numeric())
392 			continue;
393 		int n = res.to_int();
394 		if (n < 0 || n >= p_buttons.size())
395 			continue;
396 		if (p_obj && p_callback != "")
397 			p_obj->call_deferred(p_callback, n);
398 		break;
399 	};
400 	return OK;
401 };
402 
dialog_input_text(String p_title,String p_description,String p_partial,Object * p_obj,String p_callback)403 Error OS::dialog_input_text(String p_title, String p_description, String p_partial, Object *p_obj, String p_callback) {
404 
405 	ERR_FAIL_COND_V(!p_obj, FAILED);
406 	ERR_FAIL_COND_V(p_callback == "", FAILED);
407 	print("%ls\n---------\n%ls\n[%ls]:\n", p_title.c_str(), p_description.c_str(), p_partial.c_str());
408 
409 	String res = get_stdin_string().strip_edges();
410 	bool success = true;
411 	if (res == "") {
412 		res = p_partial;
413 	};
414 
415 	p_obj->call_deferred(p_callback, success, res);
416 
417 	return OK;
418 };
419 
get_static_memory_usage() const420 uint64_t OS::get_static_memory_usage() const {
421 
422 	return Memory::get_mem_usage();
423 }
get_dynamic_memory_usage() const424 uint64_t OS::get_dynamic_memory_usage() const {
425 
426 	return MemoryPool::total_memory;
427 }
428 
get_static_memory_peak_usage() const429 uint64_t OS::get_static_memory_peak_usage() const {
430 
431 	return Memory::get_mem_max_usage();
432 }
433 
set_cwd(const String & p_cwd)434 Error OS::set_cwd(const String &p_cwd) {
435 
436 	return ERR_CANT_OPEN;
437 }
438 
has_touchscreen_ui_hint() const439 bool OS::has_touchscreen_ui_hint() const {
440 
441 	//return false;
442 	return Input::get_singleton() && Input::get_singleton()->is_emulating_touch_from_mouse();
443 }
444 
get_free_static_memory() const445 uint64_t OS::get_free_static_memory() const {
446 
447 	return Memory::get_mem_available();
448 }
449 
yield()450 void OS::yield() {
451 }
452 
set_screen_orientation(ScreenOrientation p_orientation)453 void OS::set_screen_orientation(ScreenOrientation p_orientation) {
454 
455 	_orientation = p_orientation;
456 }
457 
get_screen_orientation() const458 OS::ScreenOrientation OS::get_screen_orientation() const {
459 
460 	return (OS::ScreenOrientation)_orientation;
461 }
462 
_ensure_user_data_dir()463 void OS::_ensure_user_data_dir() {
464 
465 	String dd = get_user_data_dir();
466 	DirAccess *da = DirAccess::open(dd);
467 	if (da) {
468 		memdelete(da);
469 		return;
470 	}
471 
472 	da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
473 	Error err = da->make_dir_recursive(dd);
474 	ERR_FAIL_COND_MSG(err != OK, "Error attempting to create data dir: " + dd + ".");
475 
476 	memdelete(da);
477 }
478 
set_native_icon(const String & p_filename)479 void OS::set_native_icon(const String &p_filename) {
480 }
481 
set_icon(const Ref<Image> & p_icon)482 void OS::set_icon(const Ref<Image> &p_icon) {
483 }
484 
get_model_name() const485 String OS::get_model_name() const {
486 
487 	return "GenericDevice";
488 }
489 
set_cmdline(const char * p_execpath,const List<String> & p_args)490 void OS::set_cmdline(const char *p_execpath, const List<String> &p_args) {
491 
492 	_execpath = p_execpath;
493 	_cmdline = p_args;
494 };
495 
release_rendering_thread()496 void OS::release_rendering_thread() {
497 }
498 
make_rendering_thread()499 void OS::make_rendering_thread() {
500 }
501 
swap_buffers()502 void OS::swap_buffers() {
503 }
504 
get_unique_id() const505 String OS::get_unique_id() const {
506 
507 	ERR_FAIL_V("");
508 }
509 
get_processor_count() const510 int OS::get_processor_count() const {
511 
512 	return 1;
513 }
514 
native_video_play(String p_path,float p_volume,String p_audio_track,String p_subtitle_track)515 Error OS::native_video_play(String p_path, float p_volume, String p_audio_track, String p_subtitle_track) {
516 
517 	return FAILED;
518 };
519 
native_video_is_playing() const520 bool OS::native_video_is_playing() const {
521 
522 	return false;
523 };
524 
native_video_pause()525 void OS::native_video_pause(){
526 
527 };
528 
native_video_unpause()529 void OS::native_video_unpause(){
530 
531 };
532 
native_video_stop()533 void OS::native_video_stop(){
534 
535 };
536 
set_mouse_mode(MouseMode p_mode)537 void OS::set_mouse_mode(MouseMode p_mode) {
538 }
539 
can_use_threads() const540 bool OS::can_use_threads() const {
541 
542 #ifdef NO_THREADS
543 	return false;
544 #else
545 	return true;
546 #endif
547 }
548 
get_mouse_mode() const549 OS::MouseMode OS::get_mouse_mode() const {
550 
551 	return MOUSE_MODE_VISIBLE;
552 }
553 
get_latin_keyboard_variant() const554 OS::LatinKeyboardVariant OS::get_latin_keyboard_variant() const {
555 
556 	return LATIN_KEYBOARD_QWERTY;
557 }
558 
keyboard_get_layout_count() const559 int OS::keyboard_get_layout_count() const {
560 	return 0;
561 }
562 
keyboard_get_current_layout() const563 int OS::keyboard_get_current_layout() const {
564 	return -1;
565 }
566 
keyboard_set_current_layout(int p_index)567 void OS::keyboard_set_current_layout(int p_index) {}
568 
keyboard_get_layout_language(int p_index) const569 String OS::keyboard_get_layout_language(int p_index) const {
570 	return "";
571 }
572 
keyboard_get_layout_name(int p_index) const573 String OS::keyboard_get_layout_name(int p_index) const {
574 	return "";
575 }
576 
is_joy_known(int p_device)577 bool OS::is_joy_known(int p_device) {
578 	return true;
579 }
580 
get_joy_guid(int p_device) const581 String OS::get_joy_guid(int p_device) const {
582 	return "Default Joypad";
583 }
584 
set_context(int p_context)585 void OS::set_context(int p_context) {
586 }
587 
588 OS::SwitchVSyncCallbackInThread OS::switch_vsync_function = NULL;
589 
set_use_vsync(bool p_enable)590 void OS::set_use_vsync(bool p_enable) {
591 	_use_vsync = p_enable;
592 	if (switch_vsync_function) { //if a function was set, use function
593 		switch_vsync_function(p_enable);
594 	} else { //otherwise just call here
595 		_set_use_vsync(p_enable);
596 	}
597 }
598 
is_vsync_enabled() const599 bool OS::is_vsync_enabled() const {
600 
601 	return _use_vsync;
602 }
603 
set_vsync_via_compositor(bool p_enable)604 void OS::set_vsync_via_compositor(bool p_enable) {
605 	_vsync_via_compositor = p_enable;
606 }
607 
is_vsync_via_compositor_enabled() const608 bool OS::is_vsync_via_compositor_enabled() const {
609 	return _vsync_via_compositor;
610 }
611 
get_power_state()612 OS::PowerState OS::get_power_state() {
613 	return POWERSTATE_UNKNOWN;
614 }
get_power_seconds_left()615 int OS::get_power_seconds_left() {
616 	return -1;
617 }
get_power_percent_left()618 int OS::get_power_percent_left() {
619 	return -1;
620 }
621 
set_has_server_feature_callback(HasServerFeatureCallback p_callback)622 void OS::set_has_server_feature_callback(HasServerFeatureCallback p_callback) {
623 
624 	has_server_feature_callback = p_callback;
625 }
626 
has_feature(const String & p_feature)627 bool OS::has_feature(const String &p_feature) {
628 
629 	if (p_feature == get_name())
630 		return true;
631 #ifdef DEBUG_ENABLED
632 	if (p_feature == "debug")
633 		return true;
634 #else
635 	if (p_feature == "release")
636 		return true;
637 #endif
638 #ifdef TOOLS_ENABLED
639 	if (p_feature == "editor")
640 		return true;
641 #else
642 	if (p_feature == "standalone")
643 		return true;
644 #endif
645 
646 	if (sizeof(void *) == 8 && p_feature == "64") {
647 		return true;
648 	}
649 	if (sizeof(void *) == 4 && p_feature == "32") {
650 		return true;
651 	}
652 #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__)
653 	if (p_feature == "x86_64") {
654 		return true;
655 	}
656 #elif (defined(__i386) || defined(__i386__))
657 	if (p_feature == "x86") {
658 		return true;
659 	}
660 #elif defined(__aarch64__)
661 	if (p_feature == "arm64") {
662 		return true;
663 	}
664 #elif defined(__arm__)
665 #if defined(__ARM_ARCH_7A__)
666 	if (p_feature == "armv7a" || p_feature == "armv7") {
667 		return true;
668 	}
669 #endif
670 #if defined(__ARM_ARCH_7S__)
671 	if (p_feature == "armv7s" || p_feature == "armv7") {
672 		return true;
673 	}
674 #endif
675 	if (p_feature == "arm") {
676 		return true;
677 	}
678 #endif
679 
680 	if (_check_internal_feature_support(p_feature))
681 		return true;
682 
683 	if (has_server_feature_callback && has_server_feature_callback(p_feature)) {
684 		return true;
685 	}
686 
687 	if (ProjectSettings::get_singleton()->has_custom_feature(p_feature))
688 		return true;
689 
690 	return false;
691 }
692 
center_window()693 void OS::center_window() {
694 
695 	if (is_window_fullscreen()) return;
696 
697 	Point2 sp = get_screen_position(get_current_screen());
698 	Size2 scr = get_screen_size(get_current_screen());
699 	Size2 wnd = get_real_window_size();
700 
701 	int x = sp.width + (scr.width - wnd.width) / 2;
702 	int y = sp.height + (scr.height - wnd.height) / 2;
703 
704 	set_window_position(Vector2(x, y));
705 }
706 
get_video_driver_count() const707 int OS::get_video_driver_count() const {
708 
709 	return 2;
710 }
711 
get_video_driver_name(int p_driver) const712 const char *OS::get_video_driver_name(int p_driver) const {
713 
714 	switch (p_driver) {
715 		case VIDEO_DRIVER_GLES2:
716 			return "GLES2";
717 		case VIDEO_DRIVER_GLES3:
718 		default:
719 			return "GLES3";
720 	}
721 }
722 
get_audio_driver_count() const723 int OS::get_audio_driver_count() const {
724 
725 	return AudioDriverManager::get_driver_count();
726 }
727 
get_audio_driver_name(int p_driver) const728 const char *OS::get_audio_driver_name(int p_driver) const {
729 
730 	AudioDriver *driver = AudioDriverManager::get_driver(p_driver);
731 	ERR_FAIL_COND_V_MSG(!driver, "", "Cannot get audio driver at index '" + itos(p_driver) + "'.");
732 	return AudioDriverManager::get_driver(p_driver)->get_name();
733 }
734 
set_restart_on_exit(bool p_restart,const List<String> & p_restart_arguments)735 void OS::set_restart_on_exit(bool p_restart, const List<String> &p_restart_arguments) {
736 	restart_on_exit = p_restart;
737 	restart_commandline = p_restart_arguments;
738 }
739 
is_restart_on_exit_set() const740 bool OS::is_restart_on_exit_set() const {
741 	return restart_on_exit;
742 }
743 
get_restart_on_exit_arguments() const744 List<String> OS::get_restart_on_exit_arguments() const {
745 	return restart_commandline;
746 }
747 
get_connected_midi_inputs()748 PoolStringArray OS::get_connected_midi_inputs() {
749 
750 	if (MIDIDriver::get_singleton())
751 		return MIDIDriver::get_singleton()->get_connected_inputs();
752 
753 	PoolStringArray list;
754 	ERR_FAIL_V_MSG(list, vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
755 }
756 
open_midi_inputs()757 void OS::open_midi_inputs() {
758 
759 	if (MIDIDriver::get_singleton()) {
760 		MIDIDriver::get_singleton()->open();
761 	} else {
762 		ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
763 	}
764 }
765 
close_midi_inputs()766 void OS::close_midi_inputs() {
767 
768 	if (MIDIDriver::get_singleton()) {
769 		MIDIDriver::get_singleton()->close();
770 	} else {
771 		ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
772 	}
773 }
774 
add_frame_delay(bool p_can_draw)775 void OS::add_frame_delay(bool p_can_draw) {
776 	const uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
777 	if (frame_delay) {
778 		// Add fixed frame delay to decrease CPU/GPU usage. This doesn't take
779 		// the actual frame time into account.
780 		// Due to the high fluctuation of the actual sleep duration, it's not recommended
781 		// to use this as a FPS limiter.
782 		delay_usec(frame_delay * 1000);
783 	}
784 
785 	// Add a dynamic frame delay to decrease CPU/GPU usage. This takes the
786 	// previous frame time into account for a smoother result.
787 	uint64_t dynamic_delay = 0;
788 	if (is_in_low_processor_usage_mode() || !p_can_draw) {
789 		dynamic_delay = get_low_processor_usage_mode_sleep_usec();
790 	}
791 	const int target_fps = Engine::get_singleton()->get_target_fps();
792 	if (target_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
793 		// Override the low processor usage mode sleep delay if the target FPS is lower.
794 		dynamic_delay = MAX(dynamic_delay, (uint64_t)(1000000 / target_fps));
795 	}
796 
797 	if (dynamic_delay > 0) {
798 		target_ticks += dynamic_delay;
799 		uint64_t current_ticks = get_ticks_usec();
800 
801 		if (current_ticks < target_ticks) {
802 			delay_usec(target_ticks - current_ticks);
803 		}
804 
805 		current_ticks = get_ticks_usec();
806 		target_ticks = MIN(MAX(target_ticks, current_ticks - dynamic_delay), current_ticks + dynamic_delay);
807 	}
808 }
809 
OS()810 OS::OS() {
811 	void *volatile stack_bottom;
812 
813 	restart_on_exit = false;
814 	singleton = this;
815 	_keep_screen_on = true; // set default value to true, because this had been true before godot 2.0.
816 	low_processor_usage_mode = false;
817 	low_processor_usage_mode_sleep_usec = 10000;
818 	_verbose_stdout = false;
819 	_debug_stdout = false;
820 	_no_window = false;
821 	_exit_code = 0;
822 	_orientation = SCREEN_LANDSCAPE;
823 
824 	_render_thread_mode = RENDER_THREAD_SAFE;
825 
826 	_allow_hidpi = false;
827 	_allow_layered = false;
828 	_stack_bottom = (void *)(&stack_bottom);
829 
830 	_logger = NULL;
831 
832 	has_server_feature_callback = NULL;
833 
834 	Vector<Logger *> loggers;
835 	loggers.push_back(memnew(StdLogger));
836 	_set_logger(memnew(CompositeLogger(loggers)));
837 }
838 
~OS()839 OS::~OS() {
840 	memdelete(_logger);
841 	singleton = NULL;
842 }
843