os_linuxbsd.cpp 30 KB

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