os_linuxbsd.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  1. /*************************************************************************/
  2. /* os_linuxbsd.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "os_linuxbsd.h"
  31. #include "core/io/dir_access.h"
  32. #include "main/main.h"
  33. #include "servers/display_server.h"
  34. #include "modules/modules_enabled.gen.h" // For regex.
  35. #ifdef MODULE_REGEX_ENABLED
  36. #include "modules/regex/regex.h"
  37. #endif
  38. #ifdef X11_ENABLED
  39. #include "x11/display_server_x11.h"
  40. #endif
  41. #ifdef HAVE_MNTENT
  42. #include <mntent.h>
  43. #endif
  44. #include <dlfcn.h>
  45. #include <stdio.h>
  46. #include <stdlib.h>
  47. #include <string.h>
  48. #include <sys/stat.h>
  49. #include <sys/types.h>
  50. #include <sys/utsname.h>
  51. #include <unistd.h>
  52. void OS_LinuxBSD::alert(const String &p_alert, const String &p_title) {
  53. const char *message_programs[] = { "zenity", "kdialog", "Xdialog", "xmessage" };
  54. String path = get_environment("PATH");
  55. Vector<String> path_elems = path.split(":", false);
  56. String program;
  57. for (int i = 0; i < path_elems.size(); i++) {
  58. for (uint64_t k = 0; k < sizeof(message_programs) / sizeof(char *); k++) {
  59. String tested_path = path_elems[i].path_join(message_programs[k]);
  60. if (FileAccess::exists(tested_path)) {
  61. program = tested_path;
  62. break;
  63. }
  64. }
  65. if (program.length()) {
  66. break;
  67. }
  68. }
  69. List<String> args;
  70. if (program.ends_with("zenity")) {
  71. args.push_back("--error");
  72. args.push_back("--width");
  73. args.push_back("500");
  74. args.push_back("--title");
  75. args.push_back(p_title);
  76. args.push_back("--text");
  77. args.push_back(p_alert);
  78. }
  79. if (program.ends_with("kdialog")) {
  80. args.push_back("--error");
  81. args.push_back(p_alert);
  82. args.push_back("--title");
  83. args.push_back(p_title);
  84. }
  85. if (program.ends_with("Xdialog")) {
  86. args.push_back("--title");
  87. args.push_back(p_title);
  88. args.push_back("--msgbox");
  89. args.push_back(p_alert);
  90. args.push_back("0");
  91. args.push_back("0");
  92. }
  93. if (program.ends_with("xmessage")) {
  94. args.push_back("-center");
  95. args.push_back("-title");
  96. args.push_back(p_title);
  97. args.push_back(p_alert);
  98. }
  99. if (program.length()) {
  100. execute(program, args);
  101. } else {
  102. print_line(p_alert);
  103. }
  104. }
  105. void OS_LinuxBSD::initialize() {
  106. crash_handler.initialize();
  107. OS_Unix::initialize_core();
  108. system_dir_desktop_cache = get_system_dir(SYSTEM_DIR_DESKTOP);
  109. }
  110. void OS_LinuxBSD::initialize_joypads() {
  111. #ifdef JOYDEV_ENABLED
  112. joypad = memnew(JoypadLinux(Input::get_singleton()));
  113. #endif
  114. }
  115. String OS_LinuxBSD::get_unique_id() const {
  116. static String machine_id;
  117. if (machine_id.is_empty()) {
  118. Ref<FileAccess> f = FileAccess::open("/etc/machine-id", FileAccess::READ);
  119. if (f.is_valid()) {
  120. while (machine_id.is_empty() && !f->eof_reached()) {
  121. machine_id = f->get_line().strip_edges();
  122. }
  123. }
  124. }
  125. return machine_id;
  126. }
  127. String OS_LinuxBSD::get_processor_name() const {
  128. Ref<FileAccess> f = FileAccess::open("/proc/cpuinfo", FileAccess::READ);
  129. ERR_FAIL_COND_V_MSG(f.is_null(), "", String("Couldn't open `/proc/cpuinfo` to get the CPU model name. Returning an empty string."));
  130. while (!f->eof_reached()) {
  131. const String line = f->get_line();
  132. if (line.find("model name") != -1) {
  133. return line.split(":")[1].strip_edges();
  134. }
  135. }
  136. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name from `/proc/cpuinfo`. Returning an empty string."));
  137. }
  138. void OS_LinuxBSD::finalize() {
  139. if (main_loop) {
  140. memdelete(main_loop);
  141. }
  142. main_loop = nullptr;
  143. #ifdef ALSAMIDI_ENABLED
  144. driver_alsamidi.close();
  145. #endif
  146. #ifdef JOYDEV_ENABLED
  147. if (joypad) {
  148. memdelete(joypad);
  149. }
  150. #endif
  151. }
  152. MainLoop *OS_LinuxBSD::get_main_loop() const {
  153. return main_loop;
  154. }
  155. void OS_LinuxBSD::delete_main_loop() {
  156. if (main_loop) {
  157. memdelete(main_loop);
  158. }
  159. main_loop = nullptr;
  160. }
  161. void OS_LinuxBSD::set_main_loop(MainLoop *p_main_loop) {
  162. main_loop = p_main_loop;
  163. }
  164. String OS_LinuxBSD::get_name() const {
  165. #ifdef __linux__
  166. return "Linux";
  167. #elif defined(__FreeBSD__)
  168. return "FreeBSD";
  169. #elif defined(__NetBSD__)
  170. return "NetBSD";
  171. #elif defined(__OpenBSD__)
  172. return "OpenBSD";
  173. #else
  174. return "BSD";
  175. #endif
  176. }
  177. String OS_LinuxBSD::get_systemd_os_release_info_value(const String &key) const {
  178. static String info;
  179. if (info.is_empty()) {
  180. Ref<FileAccess> f = FileAccess::open("/etc/os-release", FileAccess::READ);
  181. if (f.is_valid()) {
  182. while (!f->eof_reached()) {
  183. const String line = f->get_line();
  184. if (line.find(key) != -1) {
  185. return line.split("=")[1].strip_edges();
  186. }
  187. }
  188. }
  189. }
  190. return info;
  191. }
  192. String OS_LinuxBSD::get_distribution_name() const {
  193. static String systemd_name = get_systemd_os_release_info_value("NAME"); // returns a value for systemd users, otherwise an empty string.
  194. if (!systemd_name.is_empty()) {
  195. return systemd_name;
  196. }
  197. struct utsname uts; // returns a decent value for BSD family.
  198. uname(&uts);
  199. return uts.sysname;
  200. }
  201. String OS_LinuxBSD::get_version() const {
  202. static String systemd_version = get_systemd_os_release_info_value("VERSION"); // returns a value for systemd users, otherwise an empty string.
  203. if (!systemd_version.is_empty()) {
  204. return systemd_version;
  205. }
  206. struct utsname uts; // returns a decent value for BSD family.
  207. uname(&uts);
  208. return uts.version;
  209. }
  210. Vector<String> OS_LinuxBSD::get_video_adapter_driver_info() const {
  211. if (RenderingServer::get_singleton()->get_rendering_device() == nullptr) {
  212. return Vector<String>();
  213. }
  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. #ifdef FONTCONFIG_ENABLED
  424. if (p_feature == "system_fonts") {
  425. return font_config_initialized;
  426. }
  427. #endif
  428. if (p_feature == "pc") {
  429. return true;
  430. }
  431. return false;
  432. }
  433. uint64_t OS_LinuxBSD::get_embedded_pck_offset() const {
  434. Ref<FileAccess> f = FileAccess::open(get_executable_path(), FileAccess::READ);
  435. if (f.is_null()) {
  436. return 0;
  437. }
  438. // Read and check ELF magic number.
  439. {
  440. uint32_t magic = f->get_32();
  441. if (magic != 0x464c457f) { // 0x7F + "ELF"
  442. return 0;
  443. }
  444. }
  445. // Read program architecture bits from class field.
  446. int bits = f->get_8() * 32;
  447. // Get info about the section header table.
  448. int64_t section_table_pos;
  449. int64_t section_header_size;
  450. if (bits == 32) {
  451. section_header_size = 40;
  452. f->seek(0x20);
  453. section_table_pos = f->get_32();
  454. f->seek(0x30);
  455. } else { // 64
  456. section_header_size = 64;
  457. f->seek(0x28);
  458. section_table_pos = f->get_64();
  459. f->seek(0x3c);
  460. }
  461. int num_sections = f->get_16();
  462. int string_section_idx = f->get_16();
  463. // Load the strings table.
  464. uint8_t *strings;
  465. {
  466. // Jump to the strings section header.
  467. f->seek(section_table_pos + string_section_idx * section_header_size);
  468. // Read strings data size and offset.
  469. int64_t string_data_pos;
  470. int64_t string_data_size;
  471. if (bits == 32) {
  472. f->seek(f->get_position() + 0x10);
  473. string_data_pos = f->get_32();
  474. string_data_size = f->get_32();
  475. } else { // 64
  476. f->seek(f->get_position() + 0x18);
  477. string_data_pos = f->get_64();
  478. string_data_size = f->get_64();
  479. }
  480. // Read strings data.
  481. f->seek(string_data_pos);
  482. strings = (uint8_t *)memalloc(string_data_size);
  483. if (!strings) {
  484. return 0;
  485. }
  486. f->get_buffer(strings, string_data_size);
  487. }
  488. // Search for the "pck" section.
  489. int64_t off = 0;
  490. for (int i = 0; i < num_sections; ++i) {
  491. int64_t section_header_pos = section_table_pos + i * section_header_size;
  492. f->seek(section_header_pos);
  493. uint32_t name_offset = f->get_32();
  494. if (strcmp((char *)strings + name_offset, "pck") == 0) {
  495. if (bits == 32) {
  496. f->seek(section_header_pos + 0x10);
  497. off = f->get_32();
  498. } else { // 64
  499. f->seek(section_header_pos + 0x18);
  500. off = f->get_64();
  501. }
  502. break;
  503. }
  504. }
  505. memfree(strings);
  506. return off;
  507. }
  508. Vector<String> OS_LinuxBSD::get_system_fonts() const {
  509. #ifdef FONTCONFIG_ENABLED
  510. if (!font_config_initialized) {
  511. ERR_FAIL_V_MSG(Vector<String>(), "Unable to load fontconfig, system font support is disabled.");
  512. }
  513. HashSet<String> font_names;
  514. Vector<String> ret;
  515. static const char *allowed_formats[] = { "TrueType", "CFF" };
  516. for (size_t i = 0; i < sizeof(allowed_formats) / sizeof(const char *); i++) {
  517. FcPattern *pattern = FcPatternCreate();
  518. ERR_CONTINUE(!pattern);
  519. FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
  520. FcPatternAddString(pattern, FC_FONTFORMAT, reinterpret_cast<const FcChar8 *>(allowed_formats[i]));
  521. FcFontSet *font_set = FcFontList(config, pattern, object_set);
  522. if (font_set) {
  523. for (int j = 0; j < font_set->nfont; j++) {
  524. char *family_name = nullptr;
  525. if (FcPatternGetString(font_set->fonts[j], FC_FAMILY, 0, reinterpret_cast<FcChar8 **>(&family_name)) == FcResultMatch) {
  526. if (family_name) {
  527. font_names.insert(String::utf8(family_name));
  528. }
  529. }
  530. }
  531. FcFontSetDestroy(font_set);
  532. }
  533. FcPatternDestroy(pattern);
  534. }
  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. int OS_LinuxBSD::_weight_to_fc(int p_weight) const {
  544. if (p_weight < 150) {
  545. return FC_WEIGHT_THIN;
  546. } else if (p_weight < 250) {
  547. return FC_WEIGHT_EXTRALIGHT;
  548. } else if (p_weight < 325) {
  549. return FC_WEIGHT_LIGHT;
  550. } else if (p_weight < 375) {
  551. return FC_WEIGHT_DEMILIGHT;
  552. } else if (p_weight < 390) {
  553. return FC_WEIGHT_BOOK;
  554. } else if (p_weight < 450) {
  555. return FC_WEIGHT_REGULAR;
  556. } else if (p_weight < 550) {
  557. return FC_WEIGHT_MEDIUM;
  558. } else if (p_weight < 650) {
  559. return FC_WEIGHT_DEMIBOLD;
  560. } else if (p_weight < 750) {
  561. return FC_WEIGHT_BOLD;
  562. } else if (p_weight < 850) {
  563. return FC_WEIGHT_EXTRABOLD;
  564. } else if (p_weight < 925) {
  565. return FC_WEIGHT_BLACK;
  566. } else {
  567. return FC_WEIGHT_EXTRABLACK;
  568. }
  569. }
  570. int OS_LinuxBSD::_stretch_to_fc(int p_stretch) const {
  571. if (p_stretch < 56) {
  572. return FC_WIDTH_ULTRACONDENSED;
  573. } else if (p_stretch < 69) {
  574. return FC_WIDTH_EXTRACONDENSED;
  575. } else if (p_stretch < 81) {
  576. return FC_WIDTH_CONDENSED;
  577. } else if (p_stretch < 93) {
  578. return FC_WIDTH_SEMICONDENSED;
  579. } else if (p_stretch < 106) {
  580. return FC_WIDTH_NORMAL;
  581. } else if (p_stretch < 137) {
  582. return FC_WIDTH_SEMIEXPANDED;
  583. } else if (p_stretch < 144) {
  584. return FC_WIDTH_EXPANDED;
  585. } else if (p_stretch < 162) {
  586. return FC_WIDTH_EXTRAEXPANDED;
  587. } else {
  588. return FC_WIDTH_ULTRAEXPANDED;
  589. }
  590. }
  591. Vector<String> OS_LinuxBSD::get_system_font_path_for_text(const String &p_font_name, const String &p_text, const String &p_locale, const String &p_script, int p_weight, int p_stretch, bool p_italic) const {
  592. #ifdef FONTCONFIG_ENABLED
  593. if (!font_config_initialized) {
  594. ERR_FAIL_V_MSG(Vector<String>(), "Unable to load fontconfig, system font support is disabled.");
  595. }
  596. Vector<String> ret;
  597. FcPattern *pattern = FcPatternCreate();
  598. if (pattern) {
  599. FcPatternAddString(pattern, FC_FAMILY, reinterpret_cast<const FcChar8 *>(p_font_name.utf8().get_data()));
  600. FcPatternAddInteger(pattern, FC_WEIGHT, _weight_to_fc(p_weight));
  601. FcPatternAddInteger(pattern, FC_WIDTH, _stretch_to_fc(p_stretch));
  602. FcPatternAddInteger(pattern, FC_SLANT, p_italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN);
  603. FcCharSet *char_set = FcCharSetCreate();
  604. for (int i = 0; i < p_text.size(); i++) {
  605. FcCharSetAddChar(char_set, p_text[i]);
  606. }
  607. FcPatternAddCharSet(pattern, FC_CHARSET, char_set);
  608. FcLangSet *lang_set = FcLangSetCreate();
  609. FcLangSetAdd(lang_set, reinterpret_cast<const FcChar8 *>(p_locale.utf8().get_data()));
  610. FcPatternAddLangSet(pattern, FC_LANG, lang_set);
  611. FcConfigSubstitute(0, pattern, FcMatchPattern);
  612. FcDefaultSubstitute(pattern);
  613. FcResult result;
  614. FcPattern *match = FcFontMatch(0, pattern, &result);
  615. if (match) {
  616. char *file_name = nullptr;
  617. if (FcPatternGetString(match, FC_FILE, 0, reinterpret_cast<FcChar8 **>(&file_name)) == FcResultMatch) {
  618. if (file_name) {
  619. ret.push_back(String::utf8(file_name));
  620. }
  621. }
  622. FcPatternDestroy(match);
  623. }
  624. FcPatternDestroy(pattern);
  625. FcCharSetDestroy(char_set);
  626. FcLangSetDestroy(lang_set);
  627. }
  628. return ret;
  629. #else
  630. ERR_FAIL_V_MSG(Vector<String>(), "Godot was compiled without fontconfig, system font support is disabled.");
  631. #endif
  632. }
  633. String OS_LinuxBSD::get_system_font_path(const String &p_font_name, int p_weight, int p_stretch, bool p_italic) const {
  634. #ifdef FONTCONFIG_ENABLED
  635. if (!font_config_initialized) {
  636. ERR_FAIL_V_MSG(String(), "Unable to load fontconfig, system font support is disabled.");
  637. }
  638. String ret;
  639. FcPattern *pattern = FcPatternCreate();
  640. if (pattern) {
  641. bool allow_substitutes = (p_font_name.to_lower() == "sans-serif") || (p_font_name.to_lower() == "serif") || (p_font_name.to_lower() == "monospace") || (p_font_name.to_lower() == "cursive") || (p_font_name.to_lower() == "fantasy");
  642. FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
  643. FcPatternAddString(pattern, FC_FAMILY, reinterpret_cast<const FcChar8 *>(p_font_name.utf8().get_data()));
  644. FcPatternAddInteger(pattern, FC_WEIGHT, _weight_to_fc(p_weight));
  645. FcPatternAddInteger(pattern, FC_WIDTH, _stretch_to_fc(p_stretch));
  646. FcPatternAddInteger(pattern, FC_SLANT, p_italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN);
  647. FcConfigSubstitute(0, pattern, FcMatchPattern);
  648. FcDefaultSubstitute(pattern);
  649. FcResult result;
  650. FcPattern *match = FcFontMatch(0, pattern, &result);
  651. if (match) {
  652. if (!allow_substitutes) {
  653. char *family_name = nullptr;
  654. if (FcPatternGetString(match, FC_FAMILY, 0, reinterpret_cast<FcChar8 **>(&family_name)) == FcResultMatch) {
  655. if (family_name && String::utf8(family_name).to_lower() != p_font_name.to_lower()) {
  656. FcPatternDestroy(match);
  657. FcPatternDestroy(pattern);
  658. return String();
  659. }
  660. }
  661. }
  662. char *file_name = nullptr;
  663. if (FcPatternGetString(match, FC_FILE, 0, reinterpret_cast<FcChar8 **>(&file_name)) == FcResultMatch) {
  664. if (file_name) {
  665. ret = String::utf8(file_name);
  666. }
  667. }
  668. FcPatternDestroy(match);
  669. }
  670. FcPatternDestroy(pattern);
  671. }
  672. return ret;
  673. #else
  674. ERR_FAIL_V_MSG(String(), "Godot was compiled without fontconfig, system font support is disabled.");
  675. #endif
  676. }
  677. String OS_LinuxBSD::get_config_path() const {
  678. if (has_environment("XDG_CONFIG_HOME")) {
  679. if (get_environment("XDG_CONFIG_HOME").is_absolute_path()) {
  680. return get_environment("XDG_CONFIG_HOME");
  681. } else {
  682. 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.");
  683. return has_environment("HOME") ? get_environment("HOME").path_join(".config") : ".";
  684. }
  685. } else if (has_environment("HOME")) {
  686. return get_environment("HOME").path_join(".config");
  687. } else {
  688. return ".";
  689. }
  690. }
  691. String OS_LinuxBSD::get_data_path() const {
  692. if (has_environment("XDG_DATA_HOME")) {
  693. if (get_environment("XDG_DATA_HOME").is_absolute_path()) {
  694. return get_environment("XDG_DATA_HOME");
  695. } else {
  696. 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.");
  697. return has_environment("HOME") ? get_environment("HOME").path_join(".local/share") : get_config_path();
  698. }
  699. } else if (has_environment("HOME")) {
  700. return get_environment("HOME").path_join(".local/share");
  701. } else {
  702. return get_config_path();
  703. }
  704. }
  705. String OS_LinuxBSD::get_cache_path() const {
  706. if (has_environment("XDG_CACHE_HOME")) {
  707. if (get_environment("XDG_CACHE_HOME").is_absolute_path()) {
  708. return get_environment("XDG_CACHE_HOME");
  709. } else {
  710. 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.");
  711. return has_environment("HOME") ? get_environment("HOME").path_join(".cache") : get_config_path();
  712. }
  713. } else if (has_environment("HOME")) {
  714. return get_environment("HOME").path_join(".cache");
  715. } else {
  716. return get_config_path();
  717. }
  718. }
  719. String OS_LinuxBSD::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  720. if (p_dir == SYSTEM_DIR_DESKTOP && !system_dir_desktop_cache.is_empty()) {
  721. return system_dir_desktop_cache;
  722. }
  723. String xdgparam;
  724. switch (p_dir) {
  725. case SYSTEM_DIR_DESKTOP: {
  726. xdgparam = "DESKTOP";
  727. } break;
  728. case SYSTEM_DIR_DCIM: {
  729. xdgparam = "PICTURES";
  730. } break;
  731. case SYSTEM_DIR_DOCUMENTS: {
  732. xdgparam = "DOCUMENTS";
  733. } break;
  734. case SYSTEM_DIR_DOWNLOADS: {
  735. xdgparam = "DOWNLOAD";
  736. } break;
  737. case SYSTEM_DIR_MOVIES: {
  738. xdgparam = "VIDEOS";
  739. } break;
  740. case SYSTEM_DIR_MUSIC: {
  741. xdgparam = "MUSIC";
  742. } break;
  743. case SYSTEM_DIR_PICTURES: {
  744. xdgparam = "PICTURES";
  745. } break;
  746. case SYSTEM_DIR_RINGTONES: {
  747. xdgparam = "MUSIC";
  748. } break;
  749. }
  750. String pipe;
  751. List<String> arg;
  752. arg.push_back(xdgparam);
  753. Error err = const_cast<OS_LinuxBSD *>(this)->execute("xdg-user-dir", arg, &pipe);
  754. if (err != OK) {
  755. return ".";
  756. }
  757. return pipe.strip_edges();
  758. }
  759. void OS_LinuxBSD::run() {
  760. if (!main_loop) {
  761. return;
  762. }
  763. main_loop->initialize();
  764. //uint64_t last_ticks=get_ticks_usec();
  765. //int frames=0;
  766. //uint64_t frame=0;
  767. while (true) {
  768. DisplayServer::get_singleton()->process_events(); // get rid of pending events
  769. #ifdef JOYDEV_ENABLED
  770. joypad->process_joypads();
  771. #endif
  772. if (Main::iteration()) {
  773. break;
  774. }
  775. }
  776. main_loop->finalize();
  777. }
  778. void OS_LinuxBSD::disable_crash_handler() {
  779. crash_handler.disable();
  780. }
  781. bool OS_LinuxBSD::is_disable_crash_handler() const {
  782. return crash_handler.is_disabled();
  783. }
  784. static String get_mountpoint(const String &p_path) {
  785. struct stat s;
  786. if (stat(p_path.utf8().get_data(), &s)) {
  787. return "";
  788. }
  789. #ifdef HAVE_MNTENT
  790. dev_t dev = s.st_dev;
  791. FILE *fd = setmntent("/proc/mounts", "r");
  792. if (!fd) {
  793. return "";
  794. }
  795. struct mntent mnt;
  796. char buf[1024];
  797. size_t buflen = 1024;
  798. while (getmntent_r(fd, &mnt, buf, buflen)) {
  799. if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) {
  800. endmntent(fd);
  801. return String(mnt.mnt_dir);
  802. }
  803. }
  804. endmntent(fd);
  805. #endif
  806. return "";
  807. }
  808. Error OS_LinuxBSD::move_to_trash(const String &p_path) {
  809. String path = p_path.rstrip("/"); // Strip trailing slash when path points to a directory
  810. int err_code;
  811. List<String> args;
  812. args.push_back(path);
  813. args.push_front("trash"); // The command is `gio trash <file_name>` so we need to add it to args.
  814. Error result = execute("gio", args, nullptr, &err_code); // For GNOME based machines.
  815. if (result == OK && !err_code) {
  816. return OK;
  817. } else if (err_code == 2) {
  818. return ERR_FILE_NOT_FOUND;
  819. }
  820. args.pop_front();
  821. args.push_front("move");
  822. args.push_back("trash:/"); // The command is `kioclient5 move <file_name> trash:/`.
  823. result = execute("kioclient5", args, nullptr, &err_code); // For KDE based machines.
  824. if (result == OK && !err_code) {
  825. return OK;
  826. } else if (err_code == 2) {
  827. return ERR_FILE_NOT_FOUND;
  828. }
  829. args.pop_front();
  830. args.pop_back();
  831. result = execute("gvfs-trash", args, nullptr, &err_code); // For older Linux machines.
  832. if (result == OK && !err_code) {
  833. return OK;
  834. } else if (err_code == 2) {
  835. return ERR_FILE_NOT_FOUND;
  836. }
  837. // If the commands `kioclient5`, `gio` or `gvfs-trash` don't exist on the system we do it manually.
  838. String trash_path = "";
  839. String mnt = get_mountpoint(path);
  840. // If there is a directory "[Mountpoint]/.Trash-[UID], use it as the trash can.
  841. if (!mnt.is_empty()) {
  842. String mountpoint_trash_path(mnt + "/.Trash-" + itos(getuid()));
  843. struct stat s;
  844. if (!stat(mountpoint_trash_path.utf8().get_data(), &s)) {
  845. trash_path = mountpoint_trash_path;
  846. }
  847. }
  848. // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash" as the trash can.
  849. if (trash_path.is_empty()) {
  850. char *dhome = getenv("XDG_DATA_HOME");
  851. if (dhome) {
  852. trash_path = String::utf8(dhome) + "/Trash";
  853. }
  854. }
  855. // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash" as the trash can.
  856. if (trash_path.is_empty()) {
  857. char *home = getenv("HOME");
  858. if (home) {
  859. trash_path = String::utf8(home) + "/.local/share/Trash";
  860. }
  861. }
  862. // Issue an error if none of the previous locations is appropriate for the trash can.
  863. ERR_FAIL_COND_V_MSG(trash_path.is_empty(), FAILED, "Could not determine the trash can location");
  864. // Create needed directories for decided trash can location.
  865. {
  866. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  867. Error err = dir_access->make_dir_recursive(trash_path);
  868. // Issue an error if trash can is not created properly.
  869. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"");
  870. err = dir_access->make_dir_recursive(trash_path + "/files");
  871. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/files\"");
  872. err = dir_access->make_dir_recursive(trash_path + "/info");
  873. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/info\"");
  874. }
  875. // The trash can is successfully created, now we check that we don't exceed our file name length limit.
  876. // If the file name is too long trim it so we can add the identifying number and ".trashinfo".
  877. // Assumes that the file name length limit is 255 characters.
  878. String file_name = path.get_file();
  879. if (file_name.length() > 240) {
  880. file_name = file_name.substr(0, file_name.length() - 15);
  881. }
  882. String dest_path = trash_path + "/files/" + file_name;
  883. struct stat buff;
  884. int id_number = 0;
  885. String fn = file_name;
  886. // Checks if a resource with the same name already exist in the trash can,
  887. // if there is, add an identifying number to our resource's name.
  888. while (stat(dest_path.utf8().get_data(), &buff) == 0) {
  889. id_number++;
  890. // Added a limit to check for identically named files already on the trash can
  891. // if there are too many it could make the editor unresponsive.
  892. ERR_FAIL_COND_V_MSG(id_number > 99, FAILED, "Too many identically named resources already in the trash can.");
  893. fn = file_name + "." + itos(id_number);
  894. dest_path = trash_path + "/files/" + fn;
  895. }
  896. file_name = fn;
  897. String renamed_path = path.get_base_dir() + "/" + file_name;
  898. // Generates the .trashinfo file
  899. OS::DateTime dt = OS::get_singleton()->get_datetime(false);
  900. String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", dt.year, (int)dt.month, dt.day, dt.hour, dt.minute);
  901. timestamp = vformat("%s%02d", timestamp, dt.second); // vformat only supports up to 6 arguments.
  902. String trash_info = "[Trash Info]\nPath=" + path.uri_encode() + "\nDeletionDate=" + timestamp + "\n";
  903. {
  904. Error err;
  905. {
  906. Ref<FileAccess> file = FileAccess::open(trash_path + "/info/" + file_name + ".trashinfo", FileAccess::WRITE, &err);
  907. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't create trashinfo file: \"" + trash_path + "/info/" + file_name + ".trashinfo\"");
  908. file->store_string(trash_info);
  909. }
  910. // Rename our resource before moving it to the trash can.
  911. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  912. err = dir_access->rename(path, renamed_path);
  913. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't rename file \"" + path + "\" to \"" + renamed_path + "\"");
  914. }
  915. // Move the given resource to the trash can.
  916. // Do not use DirAccess:rename() because it can't move files across multiple mountpoints.
  917. List<String> mv_args;
  918. mv_args.push_back(renamed_path);
  919. mv_args.push_back(trash_path + "/files");
  920. {
  921. int retval;
  922. Error err = execute("mv", mv_args, nullptr, &retval);
  923. // Issue an error if "mv" failed to move the given resource to the trash can.
  924. if (err != OK || retval != 0) {
  925. ERR_PRINT("move_to_trash: Could not move the resource \"" + path + "\" to the trash can \"" + trash_path + "/files\"");
  926. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  927. err = dir_access->rename(renamed_path, path);
  928. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not rename \"" + renamed_path + "\" back to its original name: \"" + path + "\"");
  929. return FAILED;
  930. }
  931. }
  932. return OK;
  933. }
  934. OS_LinuxBSD::OS_LinuxBSD() {
  935. main_loop = nullptr;
  936. #ifdef PULSEAUDIO_ENABLED
  937. AudioDriverManager::add_driver(&driver_pulseaudio);
  938. #endif
  939. #ifdef ALSA_ENABLED
  940. AudioDriverManager::add_driver(&driver_alsa);
  941. #endif
  942. #ifdef X11_ENABLED
  943. DisplayServerX11::register_x11_driver();
  944. #endif
  945. #ifdef FONTCONFIG_ENABLED
  946. #ifdef DEBUG_ENABLED
  947. int dylibloader_verbose = 1;
  948. #else
  949. int dylibloader_verbose = 0;
  950. #endif
  951. font_config_initialized = (initialize_fontconfig(dylibloader_verbose) == 0);
  952. if (font_config_initialized) {
  953. config = FcInitLoadConfigAndFonts();
  954. if (!config) {
  955. font_config_initialized = false;
  956. }
  957. object_set = FcObjectSetBuild(FC_FAMILY, FC_FILE, nullptr);
  958. if (!object_set) {
  959. font_config_initialized = false;
  960. }
  961. }
  962. #endif // FONTCONFIG_ENABLED
  963. }
  964. OS_LinuxBSD::~OS_LinuxBSD() {
  965. #ifdef FONTCONFIG_ENABLED
  966. if (object_set) {
  967. FcObjectSetDestroy(object_set);
  968. }
  969. if (config) {
  970. FcConfigDestroy(config);
  971. }
  972. #endif // FONTCONFIG_ENABLED
  973. }