os_linuxbsd.cpp 30 KB

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