1/**************************************************************************/
2/* os_linuxbsd.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_linuxbsd.h"
32
33#include "core/io/certs_compressed.gen.h"
34#include "core/io/dir_access.h"
35#include "main/main.h"
36#include "servers/display_server.h"
37
38#ifdef X11_ENABLED
39#include "x11/display_server_x11.h"
40#endif
41
42#include "modules/modules_enabled.gen.h" // For regex.
43#ifdef MODULE_REGEX_ENABLED
44#include "modules/regex/regex.h"
45#endif
46
47#include <dlfcn.h>
48#include <stdio.h>
49#include <stdlib.h>
50#include <string.h>
51#include <sys/stat.h>
52#include <sys/types.h>
53#include <sys/utsname.h>
54#include <unistd.h>
55
56#ifdef HAVE_MNTENT
57#include <mntent.h>
58#endif
59
60void OS_LinuxBSD::alert(const String &p_alert, const String &p_title) {
61 const char *message_programs[] = { "zenity", "kdialog", "Xdialog", "xmessage" };
62
63 String path = get_environment("PATH");
64 Vector<String> path_elems = path.split(":", false);
65 String program;
66
67 for (int i = 0; i < path_elems.size(); i++) {
68 for (uint64_t k = 0; k < sizeof(message_programs) / sizeof(char *); k++) {
69 String tested_path = path_elems[i].path_join(message_programs[k]);
70
71 if (FileAccess::exists(tested_path)) {
72 program = tested_path;
73 break;
74 }
75 }
76
77 if (program.length()) {
78 break;
79 }
80 }
81
82 List<String> args;
83
84 if (program.ends_with("zenity")) {
85 args.push_back("--warning");
86 args.push_back("--width");
87 args.push_back("500");
88 args.push_back("--title");
89 args.push_back(p_title);
90 args.push_back("--text");
91 args.push_back(p_alert);
92 }
93
94 if (program.ends_with("kdialog")) {
95 // `--sorry` uses the same icon as `--warning` in Zenity.
96 // As of KDialog 22.12.1, its `--warning` options are only available for yes/no questions.
97 args.push_back("--sorry");
98 args.push_back(p_alert);
99 args.push_back("--title");
100 args.push_back(p_title);
101 }
102
103 if (program.ends_with("Xdialog")) {
104 args.push_back("--title");
105 args.push_back(p_title);
106 args.push_back("--msgbox");
107 args.push_back(p_alert);
108 args.push_back("0");
109 args.push_back("0");
110 }
111
112 if (program.ends_with("xmessage")) {
113 args.push_back("-center");
114 args.push_back("-title");
115 args.push_back(p_title);
116 args.push_back(p_alert);
117 }
118
119 if (program.length()) {
120 execute(program, args);
121 } else {
122 print_line(p_alert);
123 }
124}
125
126void OS_LinuxBSD::initialize() {
127 crash_handler.initialize();
128
129 OS_Unix::initialize_core();
130
131 system_dir_desktop_cache = get_system_dir(SYSTEM_DIR_DESKTOP);
132}
133
134void OS_LinuxBSD::initialize_joypads() {
135#ifdef JOYDEV_ENABLED
136 joypad = memnew(JoypadLinux(Input::get_singleton()));
137#endif
138}
139
140String OS_LinuxBSD::get_unique_id() const {
141 static String machine_id;
142 if (machine_id.is_empty()) {
143 Ref<FileAccess> f = FileAccess::open("/etc/machine-id", FileAccess::READ);
144 if (f.is_valid()) {
145 while (machine_id.is_empty() && !f->eof_reached()) {
146 machine_id = f->get_line().strip_edges();
147 }
148 }
149 }
150 return machine_id;
151}
152
153String OS_LinuxBSD::get_processor_name() const {
154 Ref<FileAccess> f = FileAccess::open("/proc/cpuinfo", FileAccess::READ);
155 ERR_FAIL_COND_V_MSG(f.is_null(), "", String("Couldn't open `/proc/cpuinfo` to get the CPU model name. Returning an empty string."));
156
157 while (!f->eof_reached()) {
158 const String line = f->get_line();
159 if (line.find("model name") != -1) {
160 return line.split(":")[1].strip_edges();
161 }
162 }
163
164 ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name from `/proc/cpuinfo`. Returning an empty string."));
165}
166
167bool OS_LinuxBSD::is_sandboxed() const {
168 // This function is derived from SDL:
169 // https://github.com/libsdl-org/SDL/blob/main/src/core/linux/SDL_sandbox.c#L28-L45
170
171 if (access("/.flatpak-info", F_OK) == 0) {
172 return true;
173 }
174
175 // For Snap, we check multiple variables because they might be set for
176 // unrelated reasons. This is the same thing WebKitGTK does.
177 if (has_environment("SNAP") && has_environment("SNAP_NAME") && has_environment("SNAP_REVISION")) {
178 return true;
179 }
180
181 if (access("/run/host/container-manager", F_OK) == 0) {
182 return true;
183 }
184
185 return false;
186}
187
188void OS_LinuxBSD::finalize() {
189 if (main_loop) {
190 memdelete(main_loop);
191 }
192 main_loop = nullptr;
193
194#ifdef ALSAMIDI_ENABLED
195 driver_alsamidi.close();
196#endif
197
198#ifdef JOYDEV_ENABLED
199 if (joypad) {
200 memdelete(joypad);
201 }
202#endif
203}
204
205MainLoop *OS_LinuxBSD::get_main_loop() const {
206 return main_loop;
207}
208
209void OS_LinuxBSD::delete_main_loop() {
210 if (main_loop) {
211 memdelete(main_loop);
212 }
213 main_loop = nullptr;
214}
215
216void OS_LinuxBSD::set_main_loop(MainLoop *p_main_loop) {
217 main_loop = p_main_loop;
218}
219
220String OS_LinuxBSD::get_identifier() const {
221 return "linuxbsd";
222}
223
224String OS_LinuxBSD::get_name() const {
225#ifdef __linux__
226 return "Linux";
227#elif defined(__FreeBSD__)
228 return "FreeBSD";
229#elif defined(__NetBSD__)
230 return "NetBSD";
231#elif defined(__OpenBSD__)
232 return "OpenBSD";
233#else
234 return "BSD";
235#endif
236}
237
238String OS_LinuxBSD::get_systemd_os_release_info_value(const String &key) const {
239 Ref<FileAccess> f = FileAccess::open("/etc/os-release", FileAccess::READ);
240 if (f.is_valid()) {
241 while (!f->eof_reached()) {
242 const String line = f->get_line();
243 if (line.find(key) != -1) {
244 String value = line.split("=")[1].strip_edges();
245 value = value.trim_prefix("\"");
246 return value.trim_suffix("\"");
247 }
248 }
249 }
250 return "";
251}
252
253String OS_LinuxBSD::get_distribution_name() const {
254 static String distribution_name = get_systemd_os_release_info_value("NAME"); // returns a value for systemd users, otherwise an empty string.
255 if (!distribution_name.is_empty()) {
256 return distribution_name;
257 }
258 struct utsname uts; // returns a decent value for BSD family.
259 uname(&uts);
260 distribution_name = uts.sysname;
261 return distribution_name;
262}
263
264String OS_LinuxBSD::get_version() const {
265 static String release_version = get_systemd_os_release_info_value("VERSION"); // returns a value for systemd users, otherwise an empty string.
266 if (!release_version.is_empty()) {
267 return release_version;
268 }
269 struct utsname uts; // returns a decent value for BSD family.
270 uname(&uts);
271 release_version = uts.version;
272 return release_version;
273}
274
275Vector<String> OS_LinuxBSD::get_video_adapter_driver_info() const {
276 if (RenderingServer::get_singleton() == nullptr) {
277 return Vector<String>();
278 }
279
280 static Vector<String> info;
281 if (!info.is_empty()) {
282 return info;
283 }
284
285 const String rendering_device_name = RenderingServer::get_singleton()->get_video_adapter_name(); // e.g. `NVIDIA GeForce GTX 970`
286 const String rendering_device_vendor = RenderingServer::get_singleton()->get_video_adapter_vendor(); // e.g. `NVIDIA`
287 const String card_name = rendering_device_name.trim_prefix(rendering_device_vendor).strip_edges(); // -> `GeForce GTX 970`
288
289 String vendor_device_id_mappings;
290 List<String> lspci_args;
291 lspci_args.push_back("-n");
292 Error err = const_cast<OS_LinuxBSD *>(this)->execute("lspci", lspci_args, &vendor_device_id_mappings);
293 if (err != OK || vendor_device_id_mappings.is_empty()) {
294 return Vector<String>();
295 }
296
297 // Usually found under "VGA", but for example NVIDIA mobile/laptop adapters are often listed under "3D" and some AMD adapters are under "Display".
298 const String dc_vga = "0300"; // VGA compatible controller
299 const String dc_display = "0302"; // Display controller
300 const String dc_3d = "0380"; // 3D controller
301
302 // splitting results by device class allows prioritizing, if multiple devices are found.
303 Vector<String> class_vga_device_candidates;
304 Vector<String> class_display_device_candidates;
305 Vector<String> class_3d_device_candidates;
306
307#ifdef MODULE_REGEX_ENABLED
308 RegEx regex_id_format = RegEx();
309 regex_id_format.compile("^[a-f0-9]{4}:[a-f0-9]{4}$"); // e.g. `10de:13c2`; IDs are always in hexadecimal
310#endif
311
312 Vector<String> value_lines = vendor_device_id_mappings.split("\n", false); // example: `02:00.0 0300: 10de:13c2 (rev a1)`
313 for (const String &line : value_lines) {
314 Vector<String> columns = line.split(" ", false);
315 if (columns.size() < 3) {
316 continue;
317 }
318 String device_class = columns[1].trim_suffix(":");
319 String vendor_device_id_mapping = columns[2];
320
321#ifdef MODULE_REGEX_ENABLED
322 if (regex_id_format.search(vendor_device_id_mapping).is_null()) {
323 continue;
324 }
325#endif
326
327 if (device_class == dc_vga) {
328 class_vga_device_candidates.push_back(vendor_device_id_mapping);
329 } else if (device_class == dc_display) {
330 class_display_device_candidates.push_back(vendor_device_id_mapping);
331 } else if (device_class == dc_3d) {
332 class_3d_device_candidates.push_back(vendor_device_id_mapping);
333 }
334 }
335
336 // Check results against currently used device (`card_name`), in case the user has multiple graphics cards.
337 const String device_lit = "Device"; // line of interest
338 class_vga_device_candidates = OS_LinuxBSD::lspci_device_filter(class_vga_device_candidates, dc_vga, device_lit, card_name);
339 class_display_device_candidates = OS_LinuxBSD::lspci_device_filter(class_display_device_candidates, dc_display, device_lit, card_name);
340 class_3d_device_candidates = OS_LinuxBSD::lspci_device_filter(class_3d_device_candidates, dc_3d, device_lit, card_name);
341
342 // Get driver names and filter out invalid ones, because some adapters are dummys used only for passthrough.
343 // And they have no indicator besides certain driver names.
344 const String kernel_lit = "Kernel driver in use"; // line of interest
345 const String dummys = "vfio"; // for e.g. pci passthrough dummy kernel driver `vfio-pci`
346 Vector<String> class_vga_device_drivers = OS_LinuxBSD::lspci_get_device_value(class_vga_device_candidates, kernel_lit, dummys);
347 Vector<String> class_display_device_drivers = OS_LinuxBSD::lspci_get_device_value(class_display_device_candidates, kernel_lit, dummys);
348 Vector<String> class_3d_device_drivers = OS_LinuxBSD::lspci_get_device_value(class_3d_device_candidates, kernel_lit, dummys);
349
350 String driver_name;
351 String driver_version;
352
353 // Use first valid value:
354 for (const String &driver : class_3d_device_drivers) {
355 driver_name = driver;
356 break;
357 }
358 if (driver_name.is_empty()) {
359 for (const String &driver : class_display_device_drivers) {
360 driver_name = driver;
361 break;
362 }
363 }
364 if (driver_name.is_empty()) {
365 for (const String &driver : class_vga_device_drivers) {
366 driver_name = driver;
367 break;
368 }
369 }
370
371 info.push_back(driver_name);
372
373 String modinfo;
374 List<String> modinfo_args;
375 modinfo_args.push_back(driver_name);
376 err = const_cast<OS_LinuxBSD *>(this)->execute("modinfo", modinfo_args, &modinfo);
377 if (err != OK || modinfo.is_empty()) {
378 info.push_back(""); // So that this method always either returns an empty array, or an array of length 2.
379 return info;
380 }
381 Vector<String> lines = modinfo.split("\n", false);
382 for (const String &line : lines) {
383 Vector<String> columns = line.split(":", false, 1);
384 if (columns.size() < 2) {
385 continue;
386 }
387 if (columns[0].strip_edges() == "version") {
388 driver_version = columns[1].strip_edges(); // example value: `510.85.02` on Linux/BSD
389 break;
390 }
391 }
392
393 info.push_back(driver_version);
394
395 return info;
396}
397
398Vector<String> OS_LinuxBSD::lspci_device_filter(Vector<String> vendor_device_id_mapping, String class_suffix, String check_column, String whitelist) const {
399 // NOTE: whitelist can be changed to `Vector<String>`, if the need arises.
400 const String sep = ":";
401 Vector<String> devices;
402 for (const String &mapping : vendor_device_id_mapping) {
403 String device;
404 List<String> d_args;
405 d_args.push_back("-d");
406 d_args.push_back(mapping + sep + class_suffix);
407 d_args.push_back("-vmm");
408 Error err = const_cast<OS_LinuxBSD *>(this)->execute("lspci", d_args, &device); // e.g. `lspci -d 10de:13c2:0300 -vmm`
409 if (err != OK) {
410 return Vector<String>();
411 } else if (device.is_empty()) {
412 continue;
413 }
414
415 Vector<String> device_lines = device.split("\n", false);
416 for (const String &line : device_lines) {
417 Vector<String> columns = line.split(":", false, 1);
418 if (columns.size() < 2) {
419 continue;
420 }
421 if (columns[0].strip_edges() == check_column) {
422 // for `column[0] == "Device"` this may contain `GM204 [GeForce GTX 970]`
423 bool is_valid = true;
424 if (!whitelist.is_empty()) {
425 is_valid = columns[1].strip_edges().contains(whitelist);
426 }
427 if (is_valid) {
428 devices.push_back(mapping);
429 }
430 break;
431 }
432 }
433 }
434 return devices;
435}
436
437Vector<String> OS_LinuxBSD::lspci_get_device_value(Vector<String> vendor_device_id_mapping, String check_column, String blacklist) const {
438 // NOTE: blacklist can be changed to `Vector<String>`, if the need arises.
439 const String sep = ":";
440 Vector<String> values;
441 for (const String &mapping : vendor_device_id_mapping) {
442 String device;
443 List<String> d_args;
444 d_args.push_back("-d");
445 d_args.push_back(mapping);
446 d_args.push_back("-k");
447 Error err = const_cast<OS_LinuxBSD *>(this)->execute("lspci", d_args, &device); // e.g. `lspci -d 10de:13c2 -k`
448 if (err != OK) {
449 return Vector<String>();
450 } else if (device.is_empty()) {
451 continue;
452 }
453
454 Vector<String> device_lines = device.split("\n", false);
455 for (const String &line : device_lines) {
456 Vector<String> columns = line.split(":", false, 1);
457 if (columns.size() < 2) {
458 continue;
459 }
460 if (columns[0].strip_edges() == check_column) {
461 // for `column[0] == "Kernel driver in use"` this may contain `nvidia`
462 bool is_valid = true;
463 const String value = columns[1].strip_edges();
464 if (!blacklist.is_empty()) {
465 is_valid = !value.contains(blacklist);
466 }
467 if (is_valid) {
468 values.push_back(value);
469 }
470 break;
471 }
472 }
473 }
474 return values;
475}
476
477Error OS_LinuxBSD::shell_open(String p_uri) {
478 Error ok;
479 int err_code;
480 List<String> args;
481 args.push_back(p_uri);
482
483 // Agnostic
484 ok = execute("xdg-open", args, nullptr, &err_code);
485 if (ok == OK && !err_code) {
486 return OK;
487 } else if (err_code == 2) {
488 return ERR_FILE_NOT_FOUND;
489 }
490 // GNOME
491 args.push_front("open"); // The command is `gio open`, so we need to add it to args
492 ok = execute("gio", args, nullptr, &err_code);
493 if (ok == OK && !err_code) {
494 return OK;
495 } else if (err_code == 2) {
496 return ERR_FILE_NOT_FOUND;
497 }
498 args.pop_front();
499 ok = execute("gvfs-open", args, nullptr, &err_code);
500 if (ok == OK && !err_code) {
501 return OK;
502 } else if (err_code == 2) {
503 return ERR_FILE_NOT_FOUND;
504 }
505 // KDE
506 ok = execute("kde-open5", args, nullptr, &err_code);
507 if (ok == OK && !err_code) {
508 return OK;
509 }
510 ok = execute("kde-open", args, nullptr, &err_code);
511 return !err_code ? ok : FAILED;
512}
513
514bool OS_LinuxBSD::_check_internal_feature_support(const String &p_feature) {
515#ifdef FONTCONFIG_ENABLED
516 if (p_feature == "system_fonts") {
517 return font_config_initialized;
518 }
519#endif
520
521#ifndef __linux__
522 // `bsd` includes **all** BSD, not only "other BSD" (see `get_name()`).
523 if (p_feature == "bsd") {
524 return true;
525 }
526#endif
527
528 if (p_feature == "pc") {
529 return true;
530 }
531
532 // Match against the specific OS (`linux`, `freebsd`, `netbsd`, `openbsd`).
533 if (p_feature == get_name().to_lower()) {
534 return true;
535 }
536
537 return false;
538}
539
540uint64_t OS_LinuxBSD::get_embedded_pck_offset() const {
541 Ref<FileAccess> f = FileAccess::open(get_executable_path(), FileAccess::READ);
542 if (f.is_null()) {
543 return 0;
544 }
545
546 // Read and check ELF magic number.
547 {
548 uint32_t magic = f->get_32();
549 if (magic != 0x464c457f) { // 0x7F + "ELF"
550 return 0;
551 }
552 }
553
554 // Read program architecture bits from class field.
555 int bits = f->get_8() * 32;
556
557 // Get info about the section header table.
558 int64_t section_table_pos;
559 int64_t section_header_size;
560 if (bits == 32) {
561 section_header_size = 40;
562 f->seek(0x20);
563 section_table_pos = f->get_32();
564 f->seek(0x30);
565 } else { // 64
566 section_header_size = 64;
567 f->seek(0x28);
568 section_table_pos = f->get_64();
569 f->seek(0x3c);
570 }
571 int num_sections = f->get_16();
572 int string_section_idx = f->get_16();
573
574 // Load the strings table.
575 uint8_t *strings;
576 {
577 // Jump to the strings section header.
578 f->seek(section_table_pos + string_section_idx * section_header_size);
579
580 // Read strings data size and offset.
581 int64_t string_data_pos;
582 int64_t string_data_size;
583 if (bits == 32) {
584 f->seek(f->get_position() + 0x10);
585 string_data_pos = f->get_32();
586 string_data_size = f->get_32();
587 } else { // 64
588 f->seek(f->get_position() + 0x18);
589 string_data_pos = f->get_64();
590 string_data_size = f->get_64();
591 }
592
593 // Read strings data.
594 f->seek(string_data_pos);
595 strings = (uint8_t *)memalloc(string_data_size);
596 if (!strings) {
597 return 0;
598 }
599 f->get_buffer(strings, string_data_size);
600 }
601
602 // Search for the "pck" section.
603 int64_t off = 0;
604 for (int i = 0; i < num_sections; ++i) {
605 int64_t section_header_pos = section_table_pos + i * section_header_size;
606 f->seek(section_header_pos);
607
608 uint32_t name_offset = f->get_32();
609 if (strcmp((char *)strings + name_offset, "pck") == 0) {
610 if (bits == 32) {
611 f->seek(section_header_pos + 0x10);
612 off = f->get_32();
613 } else { // 64
614 f->seek(section_header_pos + 0x18);
615 off = f->get_64();
616 }
617 break;
618 }
619 }
620 memfree(strings);
621
622 return off;
623}
624
625Vector<String> OS_LinuxBSD::get_system_fonts() const {
626#ifdef FONTCONFIG_ENABLED
627 if (!font_config_initialized) {
628 ERR_FAIL_V_MSG(Vector<String>(), "Unable to load fontconfig, system font support is disabled.");
629 }
630
631 HashSet<String> font_names;
632 Vector<String> ret;
633 static const char *allowed_formats[] = { "TrueType", "CFF" };
634 for (size_t i = 0; i < sizeof(allowed_formats) / sizeof(const char *); i++) {
635 FcPattern *pattern = FcPatternCreate();
636 ERR_CONTINUE(!pattern);
637
638 FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
639 FcPatternAddString(pattern, FC_FONTFORMAT, reinterpret_cast<const FcChar8 *>(allowed_formats[i]));
640
641 FcFontSet *font_set = FcFontList(config, pattern, object_set);
642 if (font_set) {
643 for (int j = 0; j < font_set->nfont; j++) {
644 char *family_name = nullptr;
645 if (FcPatternGetString(font_set->fonts[j], FC_FAMILY, 0, reinterpret_cast<FcChar8 **>(&family_name)) == FcResultMatch) {
646 if (family_name) {
647 font_names.insert(String::utf8(family_name));
648 }
649 }
650 }
651 FcFontSetDestroy(font_set);
652 }
653 FcPatternDestroy(pattern);
654 }
655
656 for (const String &E : font_names) {
657 ret.push_back(E);
658 }
659 return ret;
660#else
661 ERR_FAIL_V_MSG(Vector<String>(), "Godot was compiled without fontconfig, system font support is disabled.");
662#endif
663}
664
665#ifdef FONTCONFIG_ENABLED
666int OS_LinuxBSD::_weight_to_fc(int p_weight) const {
667 if (p_weight < 150) {
668 return FC_WEIGHT_THIN;
669 } else if (p_weight < 250) {
670 return FC_WEIGHT_EXTRALIGHT;
671 } else if (p_weight < 325) {
672 return FC_WEIGHT_LIGHT;
673 } else if (p_weight < 375) {
674 return FC_WEIGHT_DEMILIGHT;
675 } else if (p_weight < 390) {
676 return FC_WEIGHT_BOOK;
677 } else if (p_weight < 450) {
678 return FC_WEIGHT_REGULAR;
679 } else if (p_weight < 550) {
680 return FC_WEIGHT_MEDIUM;
681 } else if (p_weight < 650) {
682 return FC_WEIGHT_DEMIBOLD;
683 } else if (p_weight < 750) {
684 return FC_WEIGHT_BOLD;
685 } else if (p_weight < 850) {
686 return FC_WEIGHT_EXTRABOLD;
687 } else if (p_weight < 925) {
688 return FC_WEIGHT_BLACK;
689 } else {
690 return FC_WEIGHT_EXTRABLACK;
691 }
692}
693
694int OS_LinuxBSD::_stretch_to_fc(int p_stretch) const {
695 if (p_stretch < 56) {
696 return FC_WIDTH_ULTRACONDENSED;
697 } else if (p_stretch < 69) {
698 return FC_WIDTH_EXTRACONDENSED;
699 } else if (p_stretch < 81) {
700 return FC_WIDTH_CONDENSED;
701 } else if (p_stretch < 93) {
702 return FC_WIDTH_SEMICONDENSED;
703 } else if (p_stretch < 106) {
704 return FC_WIDTH_NORMAL;
705 } else if (p_stretch < 137) {
706 return FC_WIDTH_SEMIEXPANDED;
707 } else if (p_stretch < 144) {
708 return FC_WIDTH_EXPANDED;
709 } else if (p_stretch < 162) {
710 return FC_WIDTH_EXTRAEXPANDED;
711 } else {
712 return FC_WIDTH_ULTRAEXPANDED;
713 }
714}
715#endif // FONTCONFIG_ENABLED
716
717Vector<String> OS_LinuxBSD::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 {
718#ifdef FONTCONFIG_ENABLED
719 if (!font_config_initialized) {
720 ERR_FAIL_V_MSG(Vector<String>(), "Unable to load fontconfig, system font support is disabled.");
721 }
722
723 Vector<String> ret;
724 static const char *allowed_formats[] = { "TrueType", "CFF" };
725 for (size_t i = 0; i < sizeof(allowed_formats) / sizeof(const char *); i++) {
726 FcPattern *pattern = FcPatternCreate();
727 if (pattern) {
728 FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
729 FcPatternAddString(pattern, FC_FONTFORMAT, reinterpret_cast<const FcChar8 *>(allowed_formats[i]));
730 FcPatternAddString(pattern, FC_FAMILY, reinterpret_cast<const FcChar8 *>(p_font_name.utf8().get_data()));
731 FcPatternAddInteger(pattern, FC_WEIGHT, _weight_to_fc(p_weight));
732 FcPatternAddInteger(pattern, FC_WIDTH, _stretch_to_fc(p_stretch));
733 FcPatternAddInteger(pattern, FC_SLANT, p_italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN);
734
735 FcCharSet *char_set = FcCharSetCreate();
736 for (int j = 0; j < p_text.size(); j++) {
737 FcCharSetAddChar(char_set, p_text[j]);
738 }
739 FcPatternAddCharSet(pattern, FC_CHARSET, char_set);
740
741 FcLangSet *lang_set = FcLangSetCreate();
742 FcLangSetAdd(lang_set, reinterpret_cast<const FcChar8 *>(p_locale.utf8().get_data()));
743 FcPatternAddLangSet(pattern, FC_LANG, lang_set);
744
745 FcConfigSubstitute(0, pattern, FcMatchPattern);
746 FcDefaultSubstitute(pattern);
747
748 FcResult result;
749 FcPattern *match = FcFontMatch(0, pattern, &result);
750 if (match) {
751 char *file_name = nullptr;
752 if (FcPatternGetString(match, FC_FILE, 0, reinterpret_cast<FcChar8 **>(&file_name)) == FcResultMatch) {
753 if (file_name) {
754 ret.push_back(String::utf8(file_name));
755 }
756 }
757 FcPatternDestroy(match);
758 }
759 FcPatternDestroy(pattern);
760 FcCharSetDestroy(char_set);
761 FcLangSetDestroy(lang_set);
762 }
763 }
764
765 return ret;
766#else
767 ERR_FAIL_V_MSG(Vector<String>(), "Godot was compiled without fontconfig, system font support is disabled.");
768#endif
769}
770
771String OS_LinuxBSD::get_system_font_path(const String &p_font_name, int p_weight, int p_stretch, bool p_italic) const {
772#ifdef FONTCONFIG_ENABLED
773 if (!font_config_initialized) {
774 ERR_FAIL_V_MSG(String(), "Unable to load fontconfig, system font support is disabled.");
775 }
776
777 static const char *allowed_formats[] = { "TrueType", "CFF" };
778 for (size_t i = 0; i < sizeof(allowed_formats) / sizeof(const char *); i++) {
779 FcPattern *pattern = FcPatternCreate();
780 if (pattern) {
781 bool allow_substitutes = (p_font_name.to_lower() == "sans-serif") || (p_font_name.to_lower() == "serif") || (p_font_name.to_lower() == "monospace") || (p_font_name.to_lower() == "cursive") || (p_font_name.to_lower() == "fantasy");
782
783 FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
784 FcPatternAddString(pattern, FC_FONTFORMAT, reinterpret_cast<const FcChar8 *>(allowed_formats[i]));
785 FcPatternAddString(pattern, FC_FAMILY, reinterpret_cast<const FcChar8 *>(p_font_name.utf8().get_data()));
786 FcPatternAddInteger(pattern, FC_WEIGHT, _weight_to_fc(p_weight));
787 FcPatternAddInteger(pattern, FC_WIDTH, _stretch_to_fc(p_stretch));
788 FcPatternAddInteger(pattern, FC_SLANT, p_italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN);
789
790 FcConfigSubstitute(0, pattern, FcMatchPattern);
791 FcDefaultSubstitute(pattern);
792
793 FcResult result;
794 FcPattern *match = FcFontMatch(0, pattern, &result);
795 if (match) {
796 if (!allow_substitutes) {
797 char *family_name = nullptr;
798 if (FcPatternGetString(match, FC_FAMILY, 0, reinterpret_cast<FcChar8 **>(&family_name)) == FcResultMatch) {
799 if (family_name && String::utf8(family_name).to_lower() != p_font_name.to_lower()) {
800 FcPatternDestroy(match);
801 FcPatternDestroy(pattern);
802 continue;
803 }
804 }
805 }
806 char *file_name = nullptr;
807 if (FcPatternGetString(match, FC_FILE, 0, reinterpret_cast<FcChar8 **>(&file_name)) == FcResultMatch) {
808 if (file_name) {
809 String ret = String::utf8(file_name);
810 FcPatternDestroy(match);
811 FcPatternDestroy(pattern);
812 return ret;
813 }
814 }
815 FcPatternDestroy(match);
816 }
817 FcPatternDestroy(pattern);
818 }
819 }
820
821 return String();
822#else
823 ERR_FAIL_V_MSG(String(), "Godot was compiled without fontconfig, system font support is disabled.");
824#endif
825}
826
827String OS_LinuxBSD::get_config_path() const {
828 if (has_environment("XDG_CONFIG_HOME")) {
829 if (get_environment("XDG_CONFIG_HOME").is_absolute_path()) {
830 return get_environment("XDG_CONFIG_HOME");
831 } else {
832 WARN_PRINT_ONCE("`XDG_CONFIG_HOME` is a relative path. Ignoring its value and falling back to `$HOME/.config` or `.` per the XDG Base Directory specification.");
833 return has_environment("HOME") ? get_environment("HOME").path_join(".config") : ".";
834 }
835 } else if (has_environment("HOME")) {
836 return get_environment("HOME").path_join(".config");
837 } else {
838 return ".";
839 }
840}
841
842String OS_LinuxBSD::get_data_path() const {
843 if (has_environment("XDG_DATA_HOME")) {
844 if (get_environment("XDG_DATA_HOME").is_absolute_path()) {
845 return get_environment("XDG_DATA_HOME");
846 } else {
847 WARN_PRINT_ONCE("`XDG_DATA_HOME` is a relative path. Ignoring its value and falling back to `$HOME/.local/share` or `get_config_path()` per the XDG Base Directory specification.");
848 return has_environment("HOME") ? get_environment("HOME").path_join(".local/share") : get_config_path();
849 }
850 } else if (has_environment("HOME")) {
851 return get_environment("HOME").path_join(".local/share");
852 } else {
853 return get_config_path();
854 }
855}
856
857String OS_LinuxBSD::get_cache_path() const {
858 if (has_environment("XDG_CACHE_HOME")) {
859 if (get_environment("XDG_CACHE_HOME").is_absolute_path()) {
860 return get_environment("XDG_CACHE_HOME");
861 } else {
862 WARN_PRINT_ONCE("`XDG_CACHE_HOME` is a relative path. Ignoring its value and falling back to `$HOME/.cache` or `get_config_path()` per the XDG Base Directory specification.");
863 return has_environment("HOME") ? get_environment("HOME").path_join(".cache") : get_config_path();
864 }
865 } else if (has_environment("HOME")) {
866 return get_environment("HOME").path_join(".cache");
867 } else {
868 return get_config_path();
869 }
870}
871
872String OS_LinuxBSD::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
873 if (p_dir == SYSTEM_DIR_DESKTOP && !system_dir_desktop_cache.is_empty()) {
874 return system_dir_desktop_cache;
875 }
876
877 String xdgparam;
878
879 switch (p_dir) {
880 case SYSTEM_DIR_DESKTOP: {
881 xdgparam = "DESKTOP";
882 } break;
883 case SYSTEM_DIR_DCIM: {
884 xdgparam = "PICTURES";
885 } break;
886 case SYSTEM_DIR_DOCUMENTS: {
887 xdgparam = "DOCUMENTS";
888 } break;
889 case SYSTEM_DIR_DOWNLOADS: {
890 xdgparam = "DOWNLOAD";
891 } break;
892 case SYSTEM_DIR_MOVIES: {
893 xdgparam = "VIDEOS";
894 } break;
895 case SYSTEM_DIR_MUSIC: {
896 xdgparam = "MUSIC";
897 } break;
898 case SYSTEM_DIR_PICTURES: {
899 xdgparam = "PICTURES";
900 } break;
901 case SYSTEM_DIR_RINGTONES: {
902 xdgparam = "MUSIC";
903 } break;
904 }
905
906 String pipe;
907 List<String> arg;
908 arg.push_back(xdgparam);
909 Error err = const_cast<OS_LinuxBSD *>(this)->execute("xdg-user-dir", arg, &pipe);
910 if (err != OK) {
911 return ".";
912 }
913 return pipe.strip_edges();
914}
915
916void OS_LinuxBSD::run() {
917 if (!main_loop) {
918 return;
919 }
920
921 main_loop->initialize();
922
923 //uint64_t last_ticks=get_ticks_usec();
924
925 //int frames=0;
926 //uint64_t frame=0;
927
928 while (true) {
929 DisplayServer::get_singleton()->process_events(); // get rid of pending events
930#ifdef JOYDEV_ENABLED
931 joypad->process_joypads();
932#endif
933 if (Main::iteration()) {
934 break;
935 }
936 }
937
938 main_loop->finalize();
939}
940
941void OS_LinuxBSD::disable_crash_handler() {
942 crash_handler.disable();
943}
944
945bool OS_LinuxBSD::is_disable_crash_handler() const {
946 return crash_handler.is_disabled();
947}
948
949static String get_mountpoint(const String &p_path) {
950 struct stat s;
951 if (stat(p_path.utf8().get_data(), &s)) {
952 return "";
953 }
954
955#ifdef HAVE_MNTENT
956 dev_t dev = s.st_dev;
957 FILE *fd = setmntent("/proc/mounts", "r");
958 if (!fd) {
959 return "";
960 }
961
962 struct mntent mnt;
963 char buf[1024];
964 size_t buflen = 1024;
965 while (getmntent_r(fd, &mnt, buf, buflen)) {
966 if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) {
967 endmntent(fd);
968 return String(mnt.mnt_dir);
969 }
970 }
971
972 endmntent(fd);
973#endif
974 return "";
975}
976
977Error OS_LinuxBSD::move_to_trash(const String &p_path) {
978 // We try multiple methods, until we find one that works.
979 // So we only return on success until we exhausted possibilities.
980
981 String path = p_path.rstrip("/"); // Strip trailing slash when path points to a directory.
982 int err_code;
983 List<String> args;
984 args.push_back(path);
985
986 args.push_front("trash"); // The command is `gio trash <file_name>` so we add it before the path.
987 Error result = execute("gio", args, nullptr, &err_code); // For GNOME based machines.
988 if (result == OK && err_code == 0) { // Success.
989 return OK;
990 }
991
992 args.pop_front();
993 args.push_front("move");
994 args.push_back("trash:/"); // The command is `kioclient5 move <file_name> trash:/`.
995 result = execute("kioclient5", args, nullptr, &err_code); // For KDE based machines.
996 if (result == OK && err_code == 0) {
997 return OK;
998 }
999
1000 args.pop_front();
1001 args.pop_back();
1002 result = execute("gvfs-trash", args, nullptr, &err_code); // For older Linux machines.
1003 if (result == OK && err_code == 0) {
1004 return OK;
1005 }
1006
1007 // If the commands `kioclient5`, `gio` or `gvfs-trash` don't work on the system we do it manually.
1008 String trash_path = "";
1009 String mnt = get_mountpoint(path);
1010
1011 // If there is a directory "[Mountpoint]/.Trash-[UID], use it as the trash can.
1012 if (!mnt.is_empty()) {
1013 String mountpoint_trash_path(mnt + "/.Trash-" + itos(getuid()));
1014 struct stat s;
1015 if (!stat(mountpoint_trash_path.utf8().get_data(), &s)) {
1016 trash_path = mountpoint_trash_path;
1017 }
1018 }
1019
1020 // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash" as the trash can.
1021 if (trash_path.is_empty()) {
1022 char *dhome = getenv("XDG_DATA_HOME");
1023 if (dhome) {
1024 trash_path = String::utf8(dhome) + "/Trash";
1025 }
1026 }
1027
1028 // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash" as the trash can.
1029 if (trash_path.is_empty()) {
1030 char *home = getenv("HOME");
1031 if (home) {
1032 trash_path = String::utf8(home) + "/.local/share/Trash";
1033 }
1034 }
1035
1036 // Issue an error if none of the previous locations is appropriate for the trash can.
1037 ERR_FAIL_COND_V_MSG(trash_path.is_empty(), FAILED, "Could not determine the trash can location");
1038
1039 // Create needed directories for decided trash can location.
1040 {
1041 Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
1042 Error err = dir_access->make_dir_recursive(trash_path);
1043
1044 // Issue an error if trash can is not created properly.
1045 ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"");
1046 err = dir_access->make_dir_recursive(trash_path + "/files");
1047 ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/files\"");
1048 err = dir_access->make_dir_recursive(trash_path + "/info");
1049 ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/info\"");
1050 }
1051
1052 // The trash can is successfully created, now we check that we don't exceed our file name length limit.
1053 // If the file name is too long trim it so we can add the identifying number and ".trashinfo".
1054 // Assumes that the file name length limit is 255 characters.
1055 String file_name = path.get_file();
1056 if (file_name.length() > 240) {
1057 file_name = file_name.substr(0, file_name.length() - 15);
1058 }
1059
1060 String dest_path = trash_path + "/files/" + file_name;
1061 struct stat buff;
1062 int id_number = 0;
1063 String fn = file_name;
1064
1065 // Checks if a resource with the same name already exist in the trash can,
1066 // if there is, add an identifying number to our resource's name.
1067 while (stat(dest_path.utf8().get_data(), &buff) == 0) {
1068 id_number++;
1069
1070 // Added a limit to check for identically named files already on the trash can
1071 // if there are too many it could make the editor unresponsive.
1072 ERR_FAIL_COND_V_MSG(id_number > 99, FAILED, "Too many identically named resources already in the trash can.");
1073 fn = file_name + "." + itos(id_number);
1074 dest_path = trash_path + "/files/" + fn;
1075 }
1076 file_name = fn;
1077
1078 String renamed_path = path.get_base_dir() + "/" + file_name;
1079
1080 // Generates the .trashinfo file
1081 OS::DateTime dt = OS::get_singleton()->get_datetime(false);
1082 String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", dt.year, (int)dt.month, dt.day, dt.hour, dt.minute);
1083 timestamp = vformat("%s%02d", timestamp, dt.second); // vformat only supports up to 6 arguments.
1084 String trash_info = "[Trash Info]\nPath=" + path.uri_encode() + "\nDeletionDate=" + timestamp + "\n";
1085 {
1086 Error err;
1087 {
1088 Ref<FileAccess> file = FileAccess::open(trash_path + "/info/" + file_name + ".trashinfo", FileAccess::WRITE, &err);
1089 ERR_FAIL_COND_V_MSG(err != OK, err, "Can't create trashinfo file: \"" + trash_path + "/info/" + file_name + ".trashinfo\"");
1090 file->store_string(trash_info);
1091 }
1092
1093 // Rename our resource before moving it to the trash can.
1094 Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
1095 err = dir_access->rename(path, renamed_path);
1096 ERR_FAIL_COND_V_MSG(err != OK, err, "Can't rename file \"" + path + "\" to \"" + renamed_path + "\"");
1097 }
1098
1099 // Move the given resource to the trash can.
1100 // Do not use DirAccess:rename() because it can't move files across multiple mountpoints.
1101 List<String> mv_args;
1102 mv_args.push_back(renamed_path);
1103 mv_args.push_back(trash_path + "/files");
1104 {
1105 int retval;
1106 Error err = execute("mv", mv_args, nullptr, &retval);
1107
1108 // Issue an error if "mv" failed to move the given resource to the trash can.
1109 if (err != OK || retval != 0) {
1110 ERR_PRINT("move_to_trash: Could not move the resource \"" + path + "\" to the trash can \"" + trash_path + "/files\"");
1111 Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
1112 err = dir_access->rename(renamed_path, path);
1113 ERR_FAIL_COND_V_MSG(err != OK, err, "Could not rename \"" + renamed_path + "\" back to its original name: \"" + path + "\"");
1114 return FAILED;
1115 }
1116 }
1117 return OK;
1118}
1119
1120String OS_LinuxBSD::get_system_ca_certificates() {
1121 String certfile;
1122 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
1123
1124 // Compile time preferred certificates path.
1125 if (!String(_SYSTEM_CERTS_PATH).is_empty() && da->file_exists(_SYSTEM_CERTS_PATH)) {
1126 certfile = _SYSTEM_CERTS_PATH;
1127 } else if (da->file_exists("/etc/ssl/certs/ca-certificates.crt")) {
1128 // Debian/Ubuntu
1129 certfile = "/etc/ssl/certs/ca-certificates.crt";
1130 } else if (da->file_exists("/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem")) {
1131 // Fedora
1132 certfile = "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem";
1133 } else if (da->file_exists("/etc/ca-certificates/extracted/tls-ca-bundle.pem")) {
1134 // Arch Linux
1135 certfile = "/etc/ca-certificates/extracted/tls-ca-bundle.pem";
1136 } else if (da->file_exists("/var/lib/ca-certificates/ca-bundle.pem")) {
1137 // openSUSE
1138 certfile = "/var/lib/ca-certificates/ca-bundle.pem";
1139 } else if (da->file_exists("/etc/ssl/cert.pem")) {
1140 // FreeBSD/OpenBSD
1141 certfile = "/etc/ssl/cert.pem";
1142 }
1143
1144 if (certfile.is_empty()) {
1145 return "";
1146 }
1147
1148 Ref<FileAccess> f = FileAccess::open(certfile, FileAccess::READ);
1149 ERR_FAIL_COND_V_MSG(f.is_null(), "", vformat("Failed to open system CA certificates file: '%s'", certfile));
1150
1151 return f->get_as_text();
1152}
1153
1154OS_LinuxBSD::OS_LinuxBSD() {
1155 main_loop = nullptr;
1156
1157#ifdef PULSEAUDIO_ENABLED
1158 AudioDriverManager::add_driver(&driver_pulseaudio);
1159#endif
1160
1161#ifdef ALSA_ENABLED
1162 AudioDriverManager::add_driver(&driver_alsa);
1163#endif
1164
1165#ifdef X11_ENABLED
1166 DisplayServerX11::register_x11_driver();
1167#endif
1168
1169#ifdef FONTCONFIG_ENABLED
1170#ifdef SOWRAP_ENABLED
1171#ifdef DEBUG_ENABLED
1172 int dylibloader_verbose = 1;
1173#else
1174 int dylibloader_verbose = 0;
1175#endif
1176 font_config_initialized = (initialize_fontconfig(dylibloader_verbose) == 0);
1177#else
1178 font_config_initialized = true;
1179#endif
1180 if (font_config_initialized) {
1181 bool ver_ok = false;
1182 int version = FcGetVersion();
1183 ver_ok = ((version / 100 / 100) == 2 && (version / 100 % 100) >= 11) || ((version / 100 / 100) > 2); // 2.11.0
1184 print_verbose(vformat("FontConfig %d.%d.%d detected.", version / 100 / 100, version / 100 % 100, version % 100));
1185 if (!ver_ok) {
1186 font_config_initialized = false;
1187 }
1188 }
1189
1190 if (font_config_initialized) {
1191 config = FcInitLoadConfigAndFonts();
1192 if (!config) {
1193 font_config_initialized = false;
1194 }
1195 object_set = FcObjectSetBuild(FC_FAMILY, FC_FILE, nullptr);
1196 if (!object_set) {
1197 font_config_initialized = false;
1198 }
1199 }
1200#endif // FONTCONFIG_ENABLED
1201}
1202
1203OS_LinuxBSD::~OS_LinuxBSD() {
1204#ifdef FONTCONFIG_ENABLED
1205 if (object_set) {
1206 FcObjectSetDestroy(object_set);
1207 }
1208 if (config) {
1209 FcConfigDestroy(config);
1210 }
1211#endif // FONTCONFIG_ENABLED
1212}
1213