os_linuxbsd.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. /*************************************************************************/
  2. /* os_linuxbsd.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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_linuxbsd.h"
  31. #include "core/io/dir_access.h"
  32. #include "main/main.h"
  33. #include "servers/display_server.h"
  34. #include "modules/modules_enabled.gen.h" // For regex.
  35. #ifdef MODULE_REGEX_ENABLED
  36. #include "modules/regex/regex.h"
  37. #endif
  38. #ifdef X11_ENABLED
  39. #include "x11/display_server_x11.h"
  40. #endif
  41. #ifdef HAVE_MNTENT
  42. #include <mntent.h>
  43. #endif
  44. #include <dlfcn.h>
  45. #include <stdio.h>
  46. #include <stdlib.h>
  47. #include <string.h>
  48. #include <sys/stat.h>
  49. #include <sys/types.h>
  50. #include <sys/utsname.h>
  51. #include <unistd.h>
  52. #ifdef FONTCONFIG_ENABLED
  53. #include "fontconfig-so_wrap.h"
  54. #endif
  55. void OS_LinuxBSD::alert(const String &p_alert, const String &p_title) {
  56. const char *message_programs[] = { "zenity", "kdialog", "Xdialog", "xmessage" };
  57. String path = get_environment("PATH");
  58. Vector<String> path_elems = path.split(":", false);
  59. String program;
  60. for (int i = 0; i < path_elems.size(); i++) {
  61. for (uint64_t k = 0; k < sizeof(message_programs) / sizeof(char *); k++) {
  62. String tested_path = path_elems[i].path_join(message_programs[k]);
  63. if (FileAccess::exists(tested_path)) {
  64. program = tested_path;
  65. break;
  66. }
  67. }
  68. if (program.length()) {
  69. break;
  70. }
  71. }
  72. List<String> args;
  73. if (program.ends_with("zenity")) {
  74. args.push_back("--error");
  75. args.push_back("--width");
  76. args.push_back("500");
  77. args.push_back("--title");
  78. args.push_back(p_title);
  79. args.push_back("--text");
  80. args.push_back(p_alert);
  81. }
  82. if (program.ends_with("kdialog")) {
  83. args.push_back("--error");
  84. args.push_back(p_alert);
  85. args.push_back("--title");
  86. args.push_back(p_title);
  87. }
  88. if (program.ends_with("Xdialog")) {
  89. args.push_back("--title");
  90. args.push_back(p_title);
  91. args.push_back("--msgbox");
  92. args.push_back(p_alert);
  93. args.push_back("0");
  94. args.push_back("0");
  95. }
  96. if (program.ends_with("xmessage")) {
  97. args.push_back("-center");
  98. args.push_back("-title");
  99. args.push_back(p_title);
  100. args.push_back(p_alert);
  101. }
  102. if (program.length()) {
  103. execute(program, args);
  104. } else {
  105. print_line(p_alert);
  106. }
  107. }
  108. void OS_LinuxBSD::initialize() {
  109. crash_handler.initialize();
  110. OS_Unix::initialize_core();
  111. system_dir_desktop_cache = get_system_dir(SYSTEM_DIR_DESKTOP);
  112. }
  113. void OS_LinuxBSD::initialize_joypads() {
  114. #ifdef JOYDEV_ENABLED
  115. joypad = memnew(JoypadLinux(Input::get_singleton()));
  116. #endif
  117. }
  118. String OS_LinuxBSD::get_unique_id() const {
  119. static String machine_id;
  120. if (machine_id.is_empty()) {
  121. Ref<FileAccess> f = FileAccess::open("/etc/machine-id", FileAccess::READ);
  122. if (f.is_valid()) {
  123. while (machine_id.is_empty() && !f->eof_reached()) {
  124. machine_id = f->get_line().strip_edges();
  125. }
  126. }
  127. }
  128. return machine_id;
  129. }
  130. String OS_LinuxBSD::get_processor_name() const {
  131. Ref<FileAccess> f = FileAccess::open("/proc/cpuinfo", FileAccess::READ);
  132. ERR_FAIL_COND_V_MSG(f.is_null(), "", String("Couldn't open `/proc/cpuinfo` to get the CPU model name. Returning an empty string."));
  133. while (!f->eof_reached()) {
  134. const String line = f->get_line();
  135. if (line.find("model name") != -1) {
  136. return line.split(":")[1].strip_edges();
  137. }
  138. }
  139. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name from `/proc/cpuinfo`. Returning an empty string."));
  140. }
  141. void OS_LinuxBSD::finalize() {
  142. if (main_loop) {
  143. memdelete(main_loop);
  144. }
  145. main_loop = nullptr;
  146. #ifdef ALSAMIDI_ENABLED
  147. driver_alsamidi.close();
  148. #endif
  149. #ifdef JOYDEV_ENABLED
  150. if (joypad) {
  151. memdelete(joypad);
  152. }
  153. #endif
  154. }
  155. MainLoop *OS_LinuxBSD::get_main_loop() const {
  156. return main_loop;
  157. }
  158. void OS_LinuxBSD::delete_main_loop() {
  159. if (main_loop) {
  160. memdelete(main_loop);
  161. }
  162. main_loop = nullptr;
  163. }
  164. void OS_LinuxBSD::set_main_loop(MainLoop *p_main_loop) {
  165. main_loop = p_main_loop;
  166. }
  167. String OS_LinuxBSD::get_name() const {
  168. #ifdef __linux__
  169. return "Linux";
  170. #elif defined(__FreeBSD__)
  171. return "FreeBSD";
  172. #elif defined(__NetBSD__)
  173. return "NetBSD";
  174. #elif defined(__OpenBSD__)
  175. return "OpenBSD";
  176. #else
  177. return "BSD";
  178. #endif
  179. }
  180. String OS_LinuxBSD::get_systemd_os_release_info_value(const String &key) const {
  181. static String info;
  182. if (info.is_empty()) {
  183. Ref<FileAccess> f = FileAccess::open("/etc/os-release", FileAccess::READ);
  184. if (f.is_valid()) {
  185. while (!f->eof_reached()) {
  186. const String line = f->get_line();
  187. if (line.find(key) != -1) {
  188. return line.split("=")[1].strip_edges();
  189. }
  190. }
  191. }
  192. }
  193. return info;
  194. }
  195. String OS_LinuxBSD::get_distribution_name() const {
  196. static String systemd_name = get_systemd_os_release_info_value("NAME"); // returns a value for systemd users, otherwise an empty string.
  197. if (!systemd_name.is_empty()) {
  198. return systemd_name;
  199. }
  200. struct utsname uts; // returns a decent value for BSD family.
  201. uname(&uts);
  202. return uts.sysname;
  203. }
  204. String OS_LinuxBSD::get_version() const {
  205. static String systemd_version = get_systemd_os_release_info_value("VERSION"); // returns a value for systemd users, otherwise an empty string.
  206. if (!systemd_version.is_empty()) {
  207. return systemd_version;
  208. }
  209. struct utsname uts; // returns a decent value for BSD family.
  210. uname(&uts);
  211. return uts.version;
  212. }
  213. Vector<String> OS_LinuxBSD::get_video_adapter_driver_info() const {
  214. if (RenderingServer::get_singleton()->get_rendering_device() == nullptr) {
  215. return Vector<String>();
  216. }
  217. const String rendering_device_name = RenderingServer::get_singleton()->get_rendering_device()->get_device_name(); // e.g. `NVIDIA GeForce GTX 970`
  218. const String rendering_device_vendor = RenderingServer::get_singleton()->get_rendering_device()->get_device_vendor_name(); // e.g. `NVIDIA`
  219. const String card_name = rendering_device_name.trim_prefix(rendering_device_vendor).strip_edges(); // -> `GeForce GTX 970`
  220. String vendor_device_id_mappings;
  221. List<String> lspci_args;
  222. lspci_args.push_back("-n");
  223. Error err = const_cast<OS_LinuxBSD *>(this)->execute("lspci", lspci_args, &vendor_device_id_mappings);
  224. if (err != OK || vendor_device_id_mappings.is_empty()) {
  225. return Vector<String>();
  226. }
  227. // Usually found under "VGA", but for example NVIDIA mobile/laptop adapters are often listed under "3D" and some AMD adapters are under "Display".
  228. const String dc_vga = "0300"; // VGA compatible controller
  229. const String dc_display = "0302"; // Display controller
  230. const String dc_3d = "0380"; // 3D controller
  231. // splitting results by device class allows prioritizing, if multiple devices are found.
  232. Vector<String> class_vga_device_candidates;
  233. Vector<String> class_display_device_candidates;
  234. Vector<String> class_3d_device_candidates;
  235. #ifdef MODULE_REGEX_ENABLED
  236. RegEx regex_id_format = RegEx();
  237. regex_id_format.compile("^[a-f0-9]{4}:[a-f0-9]{4}$"); // e.g. `10de:13c2`; IDs are always in hexadecimal
  238. #endif
  239. Vector<String> value_lines = vendor_device_id_mappings.split("\n", false); // example: `02:00.0 0300: 10de:13c2 (rev a1)`
  240. for (const String &line : value_lines) {
  241. Vector<String> columns = line.split(" ", false);
  242. if (columns.size() < 3) {
  243. continue;
  244. }
  245. String device_class = columns[1].trim_suffix(":");
  246. String vendor_device_id_mapping = columns[2];
  247. #ifdef MODULE_REGEX_ENABLED
  248. if (regex_id_format.search(vendor_device_id_mapping).is_null()) {
  249. continue;
  250. }
  251. #endif
  252. if (device_class == dc_vga) {
  253. class_vga_device_candidates.push_back(vendor_device_id_mapping);
  254. } else if (device_class == dc_display) {
  255. class_display_device_candidates.push_back(vendor_device_id_mapping);
  256. } else if (device_class == dc_3d) {
  257. class_3d_device_candidates.push_back(vendor_device_id_mapping);
  258. }
  259. }
  260. // Check results against currently used device (`card_name`), in case the user has multiple graphics cards.
  261. const String device_lit = "Device"; // line of interest
  262. class_vga_device_candidates = OS_LinuxBSD::lspci_device_filter(class_vga_device_candidates, dc_vga, device_lit, card_name);
  263. class_display_device_candidates = OS_LinuxBSD::lspci_device_filter(class_display_device_candidates, dc_display, device_lit, card_name);
  264. class_3d_device_candidates = OS_LinuxBSD::lspci_device_filter(class_3d_device_candidates, dc_3d, device_lit, card_name);
  265. // Get driver names and filter out invalid ones, because some adapters are dummys used only for passthrough.
  266. // And they have no indicator besides certain driver names.
  267. const String kernel_lit = "Kernel driver in use"; // line of interest
  268. const String dummys = "vfio"; // for e.g. pci passthrough dummy kernel driver `vfio-pci`
  269. Vector<String> class_vga_device_drivers = OS_LinuxBSD::lspci_get_device_value(class_vga_device_candidates, kernel_lit, dummys);
  270. Vector<String> class_display_device_drivers = OS_LinuxBSD::lspci_get_device_value(class_display_device_candidates, kernel_lit, dummys);
  271. Vector<String> class_3d_device_drivers = OS_LinuxBSD::lspci_get_device_value(class_3d_device_candidates, kernel_lit, dummys);
  272. static String driver_name;
  273. static String driver_version;
  274. // Use first valid value:
  275. for (const String &driver : class_3d_device_drivers) {
  276. driver_name = driver;
  277. break;
  278. }
  279. if (driver_name.is_empty()) {
  280. for (const String &driver : class_display_device_drivers) {
  281. driver_name = driver;
  282. break;
  283. }
  284. }
  285. if (driver_name.is_empty()) {
  286. for (const String &driver : class_vga_device_drivers) {
  287. driver_name = driver;
  288. break;
  289. }
  290. }
  291. Vector<String> info;
  292. info.push_back(driver_name);
  293. String modinfo;
  294. List<String> modinfo_args;
  295. modinfo_args.push_back(driver_name);
  296. err = const_cast<OS_LinuxBSD *>(this)->execute("modinfo", modinfo_args, &modinfo);
  297. if (err != OK || modinfo.is_empty()) {
  298. info.push_back(""); // So that this method always either returns an empty array, or an array of length 2.
  299. return info;
  300. }
  301. Vector<String> lines = modinfo.split("\n", false);
  302. for (const String &line : lines) {
  303. Vector<String> columns = line.split(":", false, 1);
  304. if (columns.size() < 2) {
  305. continue;
  306. }
  307. if (columns[0].strip_edges() == "version") {
  308. driver_version = columns[1].strip_edges(); // example value: `510.85.02` on Linux/BSD
  309. break;
  310. }
  311. }
  312. info.push_back(driver_version);
  313. return info;
  314. }
  315. Vector<String> OS_LinuxBSD::lspci_device_filter(Vector<String> vendor_device_id_mapping, String class_suffix, String check_column, String whitelist) const {
  316. // NOTE: whitelist can be changed to `Vector<String>`, if the need arises.
  317. const String sep = ":";
  318. Vector<String> devices;
  319. for (const String &mapping : vendor_device_id_mapping) {
  320. String device;
  321. List<String> d_args;
  322. d_args.push_back("-d");
  323. d_args.push_back(mapping + sep + class_suffix);
  324. d_args.push_back("-vmm");
  325. Error err = const_cast<OS_LinuxBSD *>(this)->execute("lspci", d_args, &device); // e.g. `lspci -d 10de:13c2:0300 -vmm`
  326. if (err != OK) {
  327. return Vector<String>();
  328. } else if (device.is_empty()) {
  329. continue;
  330. }
  331. Vector<String> device_lines = device.split("\n", false);
  332. for (const String &line : device_lines) {
  333. Vector<String> columns = line.split(":", false, 1);
  334. if (columns.size() < 2) {
  335. continue;
  336. }
  337. if (columns[0].strip_edges() == check_column) {
  338. // for `column[0] == "Device"` this may contain `GM204 [GeForce GTX 970]`
  339. bool is_valid = true;
  340. if (!whitelist.is_empty()) {
  341. is_valid = columns[1].strip_edges().contains(whitelist);
  342. }
  343. if (is_valid) {
  344. devices.push_back(mapping);
  345. }
  346. break;
  347. }
  348. }
  349. }
  350. return devices;
  351. }
  352. Vector<String> OS_LinuxBSD::lspci_get_device_value(Vector<String> vendor_device_id_mapping, String check_column, String blacklist) const {
  353. // NOTE: blacklist can be changed to `Vector<String>`, if the need arises.
  354. const String sep = ":";
  355. Vector<String> values;
  356. for (const String &mapping : vendor_device_id_mapping) {
  357. String device;
  358. List<String> d_args;
  359. d_args.push_back("-d");
  360. d_args.push_back(mapping);
  361. d_args.push_back("-k");
  362. Error err = const_cast<OS_LinuxBSD *>(this)->execute("lspci", d_args, &device); // e.g. `lspci -d 10de:13c2 -k`
  363. if (err != OK) {
  364. return Vector<String>();
  365. } else if (device.is_empty()) {
  366. continue;
  367. }
  368. Vector<String> device_lines = device.split("\n", false);
  369. for (const String &line : device_lines) {
  370. Vector<String> columns = line.split(":", false, 1);
  371. if (columns.size() < 2) {
  372. continue;
  373. }
  374. if (columns[0].strip_edges() == check_column) {
  375. // for `column[0] == "Kernel driver in use"` this may contain `nvidia`
  376. bool is_valid = true;
  377. const String value = columns[1].strip_edges();
  378. if (!blacklist.is_empty()) {
  379. is_valid = !value.contains(blacklist);
  380. }
  381. if (is_valid) {
  382. values.push_back(value);
  383. }
  384. break;
  385. }
  386. }
  387. }
  388. return values;
  389. }
  390. Error OS_LinuxBSD::shell_open(String p_uri) {
  391. Error ok;
  392. int err_code;
  393. List<String> args;
  394. args.push_back(p_uri);
  395. // Agnostic
  396. ok = execute("xdg-open", args, nullptr, &err_code);
  397. if (ok == OK && !err_code) {
  398. return OK;
  399. } else if (err_code == 2) {
  400. return ERR_FILE_NOT_FOUND;
  401. }
  402. // GNOME
  403. args.push_front("open"); // The command is `gio open`, so we need to add it to args
  404. ok = execute("gio", args, nullptr, &err_code);
  405. if (ok == OK && !err_code) {
  406. return OK;
  407. } else if (err_code == 2) {
  408. return ERR_FILE_NOT_FOUND;
  409. }
  410. args.pop_front();
  411. ok = execute("gvfs-open", args, nullptr, &err_code);
  412. if (ok == OK && !err_code) {
  413. return OK;
  414. } else if (err_code == 2) {
  415. return ERR_FILE_NOT_FOUND;
  416. }
  417. // KDE
  418. ok = execute("kde-open5", args, nullptr, &err_code);
  419. if (ok == OK && !err_code) {
  420. return OK;
  421. }
  422. ok = execute("kde-open", args, nullptr, &err_code);
  423. return !err_code ? ok : FAILED;
  424. }
  425. bool OS_LinuxBSD::_check_internal_feature_support(const String &p_feature) {
  426. #ifdef FONTCONFIG_ENABLED
  427. if (p_feature == "system_fonts") {
  428. return font_config_initialized;
  429. }
  430. #endif
  431. if (p_feature == "pc") {
  432. return true;
  433. }
  434. return false;
  435. }
  436. uint64_t OS_LinuxBSD::get_embedded_pck_offset() const {
  437. Ref<FileAccess> f = FileAccess::open(get_executable_path(), FileAccess::READ);
  438. if (f.is_null()) {
  439. return 0;
  440. }
  441. // Read and check ELF magic number.
  442. {
  443. uint32_t magic = f->get_32();
  444. if (magic != 0x464c457f) { // 0x7F + "ELF"
  445. return 0;
  446. }
  447. }
  448. // Read program architecture bits from class field.
  449. int bits = f->get_8() * 32;
  450. // Get info about the section header table.
  451. int64_t section_table_pos;
  452. int64_t section_header_size;
  453. if (bits == 32) {
  454. section_header_size = 40;
  455. f->seek(0x20);
  456. section_table_pos = f->get_32();
  457. f->seek(0x30);
  458. } else { // 64
  459. section_header_size = 64;
  460. f->seek(0x28);
  461. section_table_pos = f->get_64();
  462. f->seek(0x3c);
  463. }
  464. int num_sections = f->get_16();
  465. int string_section_idx = f->get_16();
  466. // Load the strings table.
  467. uint8_t *strings;
  468. {
  469. // Jump to the strings section header.
  470. f->seek(section_table_pos + string_section_idx * section_header_size);
  471. // Read strings data size and offset.
  472. int64_t string_data_pos;
  473. int64_t string_data_size;
  474. if (bits == 32) {
  475. f->seek(f->get_position() + 0x10);
  476. string_data_pos = f->get_32();
  477. string_data_size = f->get_32();
  478. } else { // 64
  479. f->seek(f->get_position() + 0x18);
  480. string_data_pos = f->get_64();
  481. string_data_size = f->get_64();
  482. }
  483. // Read strings data.
  484. f->seek(string_data_pos);
  485. strings = (uint8_t *)memalloc(string_data_size);
  486. if (!strings) {
  487. return 0;
  488. }
  489. f->get_buffer(strings, string_data_size);
  490. }
  491. // Search for the "pck" section.
  492. int64_t off = 0;
  493. for (int i = 0; i < num_sections; ++i) {
  494. int64_t section_header_pos = section_table_pos + i * section_header_size;
  495. f->seek(section_header_pos);
  496. uint32_t name_offset = f->get_32();
  497. if (strcmp((char *)strings + name_offset, "pck") == 0) {
  498. if (bits == 32) {
  499. f->seek(section_header_pos + 0x10);
  500. off = f->get_32();
  501. } else { // 64
  502. f->seek(section_header_pos + 0x18);
  503. off = f->get_64();
  504. }
  505. break;
  506. }
  507. }
  508. memfree(strings);
  509. return off;
  510. }
  511. Vector<String> OS_LinuxBSD::get_system_fonts() const {
  512. #ifdef FONTCONFIG_ENABLED
  513. if (!font_config_initialized) {
  514. ERR_FAIL_V_MSG(Vector<String>(), "Unable to load fontconfig, system font support is disabled.");
  515. }
  516. HashSet<String> font_names;
  517. Vector<String> ret;
  518. FcConfig *config = FcInitLoadConfigAndFonts();
  519. ERR_FAIL_COND_V(!config, ret);
  520. FcObjectSet *object_set = FcObjectSetBuild(FC_FAMILY, nullptr);
  521. ERR_FAIL_COND_V(!object_set, ret);
  522. static const char *allowed_formats[] = { "TrueType", "CFF" };
  523. for (size_t i = 0; i < sizeof(allowed_formats) / sizeof(const char *); i++) {
  524. FcPattern *pattern = FcPatternCreate();
  525. ERR_CONTINUE(!pattern);
  526. FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
  527. FcPatternAddString(pattern, FC_FONTFORMAT, reinterpret_cast<const FcChar8 *>(allowed_formats[i]));
  528. FcFontSet *font_set = FcFontList(config, pattern, object_set);
  529. if (font_set) {
  530. for (int j = 0; j < font_set->nfont; j++) {
  531. char *family_name = nullptr;
  532. if (FcPatternGetString(font_set->fonts[j], FC_FAMILY, 0, reinterpret_cast<FcChar8 **>(&family_name)) == FcResultMatch) {
  533. if (family_name) {
  534. font_names.insert(String::utf8(family_name));
  535. }
  536. }
  537. }
  538. FcFontSetDestroy(font_set);
  539. }
  540. FcPatternDestroy(pattern);
  541. }
  542. FcObjectSetDestroy(object_set);
  543. FcConfigDestroy(config);
  544. for (const String &E : font_names) {
  545. ret.push_back(E);
  546. }
  547. return ret;
  548. #else
  549. ERR_FAIL_V_MSG(Vector<String>(), "Godot was compiled without fontconfig, system font support is disabled.");
  550. #endif
  551. }
  552. String OS_LinuxBSD::get_system_font_path(const String &p_font_name, bool p_bold, bool p_italic) const {
  553. #ifdef FONTCONFIG_ENABLED
  554. if (!font_config_initialized) {
  555. ERR_FAIL_V_MSG(String(), "Unable to load fontconfig, system font support is disabled.");
  556. }
  557. String ret;
  558. FcConfig *config = FcInitLoadConfigAndFonts();
  559. ERR_FAIL_COND_V(!config, ret);
  560. FcObjectSet *object_set = FcObjectSetBuild(FC_FAMILY, FC_FILE, nullptr);
  561. ERR_FAIL_COND_V(!object_set, ret);
  562. FcPattern *pattern = FcPatternCreate();
  563. if (pattern) {
  564. FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
  565. FcPatternAddString(pattern, FC_FAMILY, reinterpret_cast<const FcChar8 *>(p_font_name.utf8().get_data()));
  566. FcPatternAddInteger(pattern, FC_WEIGHT, p_bold ? FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL);
  567. FcPatternAddInteger(pattern, FC_SLANT, p_italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN);
  568. FcConfigSubstitute(0, pattern, FcMatchPattern);
  569. FcDefaultSubstitute(pattern);
  570. FcResult result;
  571. FcPattern *match = FcFontMatch(0, pattern, &result);
  572. if (match) {
  573. char *file_name = nullptr;
  574. if (FcPatternGetString(match, FC_FILE, 0, reinterpret_cast<FcChar8 **>(&file_name)) == FcResultMatch) {
  575. if (file_name) {
  576. ret = String::utf8(file_name);
  577. }
  578. }
  579. FcPatternDestroy(match);
  580. }
  581. FcPatternDestroy(pattern);
  582. }
  583. FcObjectSetDestroy(object_set);
  584. FcConfigDestroy(config);
  585. return ret;
  586. #else
  587. ERR_FAIL_V_MSG(String(), "Godot was compiled without fontconfig, system font support is disabled.");
  588. #endif
  589. }
  590. String OS_LinuxBSD::get_config_path() const {
  591. if (has_environment("XDG_CONFIG_HOME")) {
  592. if (get_environment("XDG_CONFIG_HOME").is_absolute_path()) {
  593. return get_environment("XDG_CONFIG_HOME");
  594. } else {
  595. 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.");
  596. return has_environment("HOME") ? get_environment("HOME").path_join(".config") : ".";
  597. }
  598. } else if (has_environment("HOME")) {
  599. return get_environment("HOME").path_join(".config");
  600. } else {
  601. return ".";
  602. }
  603. }
  604. String OS_LinuxBSD::get_data_path() const {
  605. if (has_environment("XDG_DATA_HOME")) {
  606. if (get_environment("XDG_DATA_HOME").is_absolute_path()) {
  607. return get_environment("XDG_DATA_HOME");
  608. } else {
  609. 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.");
  610. return has_environment("HOME") ? get_environment("HOME").path_join(".local/share") : get_config_path();
  611. }
  612. } else if (has_environment("HOME")) {
  613. return get_environment("HOME").path_join(".local/share");
  614. } else {
  615. return get_config_path();
  616. }
  617. }
  618. String OS_LinuxBSD::get_cache_path() const {
  619. if (has_environment("XDG_CACHE_HOME")) {
  620. if (get_environment("XDG_CACHE_HOME").is_absolute_path()) {
  621. return get_environment("XDG_CACHE_HOME");
  622. } else {
  623. 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.");
  624. return has_environment("HOME") ? get_environment("HOME").path_join(".cache") : get_config_path();
  625. }
  626. } else if (has_environment("HOME")) {
  627. return get_environment("HOME").path_join(".cache");
  628. } else {
  629. return get_config_path();
  630. }
  631. }
  632. String OS_LinuxBSD::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  633. if (p_dir == SYSTEM_DIR_DESKTOP && !system_dir_desktop_cache.is_empty()) {
  634. return system_dir_desktop_cache;
  635. }
  636. String xdgparam;
  637. switch (p_dir) {
  638. case SYSTEM_DIR_DESKTOP: {
  639. xdgparam = "DESKTOP";
  640. } break;
  641. case SYSTEM_DIR_DCIM: {
  642. xdgparam = "PICTURES";
  643. } break;
  644. case SYSTEM_DIR_DOCUMENTS: {
  645. xdgparam = "DOCUMENTS";
  646. } break;
  647. case SYSTEM_DIR_DOWNLOADS: {
  648. xdgparam = "DOWNLOAD";
  649. } break;
  650. case SYSTEM_DIR_MOVIES: {
  651. xdgparam = "VIDEOS";
  652. } break;
  653. case SYSTEM_DIR_MUSIC: {
  654. xdgparam = "MUSIC";
  655. } break;
  656. case SYSTEM_DIR_PICTURES: {
  657. xdgparam = "PICTURES";
  658. } break;
  659. case SYSTEM_DIR_RINGTONES: {
  660. xdgparam = "MUSIC";
  661. } break;
  662. }
  663. String pipe;
  664. List<String> arg;
  665. arg.push_back(xdgparam);
  666. Error err = const_cast<OS_LinuxBSD *>(this)->execute("xdg-user-dir", arg, &pipe);
  667. if (err != OK) {
  668. return ".";
  669. }
  670. return pipe.strip_edges();
  671. }
  672. void OS_LinuxBSD::run() {
  673. if (!main_loop) {
  674. return;
  675. }
  676. main_loop->initialize();
  677. //uint64_t last_ticks=get_ticks_usec();
  678. //int frames=0;
  679. //uint64_t frame=0;
  680. while (true) {
  681. DisplayServer::get_singleton()->process_events(); // get rid of pending events
  682. #ifdef JOYDEV_ENABLED
  683. joypad->process_joypads();
  684. #endif
  685. if (Main::iteration()) {
  686. break;
  687. }
  688. }
  689. main_loop->finalize();
  690. }
  691. void OS_LinuxBSD::disable_crash_handler() {
  692. crash_handler.disable();
  693. }
  694. bool OS_LinuxBSD::is_disable_crash_handler() const {
  695. return crash_handler.is_disabled();
  696. }
  697. static String get_mountpoint(const String &p_path) {
  698. struct stat s;
  699. if (stat(p_path.utf8().get_data(), &s)) {
  700. return "";
  701. }
  702. #ifdef HAVE_MNTENT
  703. dev_t dev = s.st_dev;
  704. FILE *fd = setmntent("/proc/mounts", "r");
  705. if (!fd) {
  706. return "";
  707. }
  708. struct mntent mnt;
  709. char buf[1024];
  710. size_t buflen = 1024;
  711. while (getmntent_r(fd, &mnt, buf, buflen)) {
  712. if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) {
  713. endmntent(fd);
  714. return String(mnt.mnt_dir);
  715. }
  716. }
  717. endmntent(fd);
  718. #endif
  719. return "";
  720. }
  721. Error OS_LinuxBSD::move_to_trash(const String &p_path) {
  722. String path = p_path.rstrip("/"); // Strip trailing slash when path points to a directory
  723. int err_code;
  724. List<String> args;
  725. args.push_back(path);
  726. args.push_front("trash"); // The command is `gio trash <file_name>` so we need to add it to args.
  727. Error result = execute("gio", args, nullptr, &err_code); // For GNOME based machines.
  728. if (result == OK && !err_code) {
  729. return OK;
  730. } else if (err_code == 2) {
  731. return ERR_FILE_NOT_FOUND;
  732. }
  733. args.pop_front();
  734. args.push_front("move");
  735. args.push_back("trash:/"); // The command is `kioclient5 move <file_name> trash:/`.
  736. result = execute("kioclient5", args, nullptr, &err_code); // For KDE based machines.
  737. if (result == OK && !err_code) {
  738. return OK;
  739. } else if (err_code == 2) {
  740. return ERR_FILE_NOT_FOUND;
  741. }
  742. args.pop_front();
  743. args.pop_back();
  744. result = execute("gvfs-trash", args, nullptr, &err_code); // For older Linux machines.
  745. if (result == OK && !err_code) {
  746. return OK;
  747. } else if (err_code == 2) {
  748. return ERR_FILE_NOT_FOUND;
  749. }
  750. // If the commands `kioclient5`, `gio` or `gvfs-trash` don't exist on the system we do it manually.
  751. String trash_path = "";
  752. String mnt = get_mountpoint(path);
  753. // If there is a directory "[Mountpoint]/.Trash-[UID], use it as the trash can.
  754. if (!mnt.is_empty()) {
  755. String mountpoint_trash_path(mnt + "/.Trash-" + itos(getuid()));
  756. struct stat s;
  757. if (!stat(mountpoint_trash_path.utf8().get_data(), &s)) {
  758. trash_path = mountpoint_trash_path;
  759. }
  760. }
  761. // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash" as the trash can.
  762. if (trash_path.is_empty()) {
  763. char *dhome = getenv("XDG_DATA_HOME");
  764. if (dhome) {
  765. trash_path = String::utf8(dhome) + "/Trash";
  766. }
  767. }
  768. // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash" as the trash can.
  769. if (trash_path.is_empty()) {
  770. char *home = getenv("HOME");
  771. if (home) {
  772. trash_path = String::utf8(home) + "/.local/share/Trash";
  773. }
  774. }
  775. // Issue an error if none of the previous locations is appropriate for the trash can.
  776. ERR_FAIL_COND_V_MSG(trash_path.is_empty(), FAILED, "Could not determine the trash can location");
  777. // Create needed directories for decided trash can location.
  778. {
  779. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  780. Error err = dir_access->make_dir_recursive(trash_path);
  781. // Issue an error if trash can is not created properly.
  782. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"");
  783. err = dir_access->make_dir_recursive(trash_path + "/files");
  784. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/files\"");
  785. err = dir_access->make_dir_recursive(trash_path + "/info");
  786. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/info\"");
  787. }
  788. // The trash can is successfully created, now we check that we don't exceed our file name length limit.
  789. // If the file name is too long trim it so we can add the identifying number and ".trashinfo".
  790. // Assumes that the file name length limit is 255 characters.
  791. String file_name = path.get_file();
  792. if (file_name.length() > 240) {
  793. file_name = file_name.substr(0, file_name.length() - 15);
  794. }
  795. String dest_path = trash_path + "/files/" + file_name;
  796. struct stat buff;
  797. int id_number = 0;
  798. String fn = file_name;
  799. // Checks if a resource with the same name already exist in the trash can,
  800. // if there is, add an identifying number to our resource's name.
  801. while (stat(dest_path.utf8().get_data(), &buff) == 0) {
  802. id_number++;
  803. // Added a limit to check for identically named files already on the trash can
  804. // if there are too many it could make the editor unresponsive.
  805. ERR_FAIL_COND_V_MSG(id_number > 99, FAILED, "Too many identically named resources already in the trash can.");
  806. fn = file_name + "." + itos(id_number);
  807. dest_path = trash_path + "/files/" + fn;
  808. }
  809. file_name = fn;
  810. String renamed_path = path.get_base_dir() + "/" + file_name;
  811. // Generates the .trashinfo file
  812. OS::DateTime dt = OS::get_singleton()->get_datetime(false);
  813. String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", dt.year, (int)dt.month, dt.day, dt.hour, dt.minute);
  814. timestamp = vformat("%s%02d", timestamp, dt.second); // vformat only supports up to 6 arguments.
  815. String trash_info = "[Trash Info]\nPath=" + path.uri_encode() + "\nDeletionDate=" + timestamp + "\n";
  816. {
  817. Error err;
  818. {
  819. Ref<FileAccess> file = FileAccess::open(trash_path + "/info/" + file_name + ".trashinfo", FileAccess::WRITE, &err);
  820. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't create trashinfo file: \"" + trash_path + "/info/" + file_name + ".trashinfo\"");
  821. file->store_string(trash_info);
  822. }
  823. // Rename our resource before moving it to the trash can.
  824. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  825. err = dir_access->rename(path, renamed_path);
  826. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't rename file \"" + path + "\" to \"" + renamed_path + "\"");
  827. }
  828. // Move the given resource to the trash can.
  829. // Do not use DirAccess:rename() because it can't move files across multiple mountpoints.
  830. List<String> mv_args;
  831. mv_args.push_back(renamed_path);
  832. mv_args.push_back(trash_path + "/files");
  833. {
  834. int retval;
  835. Error err = execute("mv", mv_args, nullptr, &retval);
  836. // Issue an error if "mv" failed to move the given resource to the trash can.
  837. if (err != OK || retval != 0) {
  838. ERR_PRINT("move_to_trash: Could not move the resource \"" + path + "\" to the trash can \"" + trash_path + "/files\"");
  839. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  840. err = dir_access->rename(renamed_path, path);
  841. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not rename \"" + renamed_path + "\" back to its original name: \"" + path + "\"");
  842. return FAILED;
  843. }
  844. }
  845. return OK;
  846. }
  847. OS_LinuxBSD::OS_LinuxBSD() {
  848. main_loop = nullptr;
  849. #ifdef PULSEAUDIO_ENABLED
  850. AudioDriverManager::add_driver(&driver_pulseaudio);
  851. #endif
  852. #ifdef ALSA_ENABLED
  853. AudioDriverManager::add_driver(&driver_alsa);
  854. #endif
  855. #ifdef X11_ENABLED
  856. DisplayServerX11::register_x11_driver();
  857. #endif
  858. #ifdef FONTCONFIG_ENABLED
  859. #ifdef DEBUG_ENABLED
  860. int dylibloader_verbose = 1;
  861. #else
  862. int dylibloader_verbose = 0;
  863. #endif
  864. font_config_initialized = (initialize_fontconfig(dylibloader_verbose) == 0);
  865. #endif // FONTCONFIG_ENABLED
  866. }