os_linuxbsd.cpp 30 KB

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