os_linuxbsd.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. /**************************************************************************/
  2. /* os_linuxbsd.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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("--warning");
  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. // `--sorry` uses the same icon as `--warning` in Zenity.
  81. // As of KDialog 22.12.1, its `--warning` options are only available for yes/no questions.
  82. args.push_back("--sorry");
  83. args.push_back(p_alert);
  84. args.push_back("--title");
  85. args.push_back(p_title);
  86. }
  87. if (program.ends_with("Xdialog")) {
  88. args.push_back("--title");
  89. args.push_back(p_title);
  90. args.push_back("--msgbox");
  91. args.push_back(p_alert);
  92. args.push_back("0");
  93. args.push_back("0");
  94. }
  95. if (program.ends_with("xmessage")) {
  96. args.push_back("-center");
  97. args.push_back("-title");
  98. args.push_back(p_title);
  99. args.push_back(p_alert);
  100. }
  101. if (program.length()) {
  102. execute(program, args);
  103. } else {
  104. print_line(p_alert);
  105. }
  106. }
  107. void OS_LinuxBSD::initialize() {
  108. crash_handler.initialize();
  109. OS_Unix::initialize_core();
  110. system_dir_desktop_cache = get_system_dir(SYSTEM_DIR_DESKTOP);
  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. #ifdef FONTCONFIG_ENABLED
  426. if (p_feature == "system_fonts") {
  427. return font_config_initialized;
  428. }
  429. #endif
  430. if (p_feature == "pc") {
  431. return true;
  432. }
  433. return false;
  434. }
  435. uint64_t OS_LinuxBSD::get_embedded_pck_offset() const {
  436. Ref<FileAccess> f = FileAccess::open(get_executable_path(), FileAccess::READ);
  437. if (f.is_null()) {
  438. return 0;
  439. }
  440. // Read and check ELF magic number.
  441. {
  442. uint32_t magic = f->get_32();
  443. if (magic != 0x464c457f) { // 0x7F + "ELF"
  444. return 0;
  445. }
  446. }
  447. // Read program architecture bits from class field.
  448. int bits = f->get_8() * 32;
  449. // Get info about the section header table.
  450. int64_t section_table_pos;
  451. int64_t section_header_size;
  452. if (bits == 32) {
  453. section_header_size = 40;
  454. f->seek(0x20);
  455. section_table_pos = f->get_32();
  456. f->seek(0x30);
  457. } else { // 64
  458. section_header_size = 64;
  459. f->seek(0x28);
  460. section_table_pos = f->get_64();
  461. f->seek(0x3c);
  462. }
  463. int num_sections = f->get_16();
  464. int string_section_idx = f->get_16();
  465. // Load the strings table.
  466. uint8_t *strings;
  467. {
  468. // Jump to the strings section header.
  469. f->seek(section_table_pos + string_section_idx * section_header_size);
  470. // Read strings data size and offset.
  471. int64_t string_data_pos;
  472. int64_t string_data_size;
  473. if (bits == 32) {
  474. f->seek(f->get_position() + 0x10);
  475. string_data_pos = f->get_32();
  476. string_data_size = f->get_32();
  477. } else { // 64
  478. f->seek(f->get_position() + 0x18);
  479. string_data_pos = f->get_64();
  480. string_data_size = f->get_64();
  481. }
  482. // Read strings data.
  483. f->seek(string_data_pos);
  484. strings = (uint8_t *)memalloc(string_data_size);
  485. if (!strings) {
  486. return 0;
  487. }
  488. f->get_buffer(strings, string_data_size);
  489. }
  490. // Search for the "pck" section.
  491. int64_t off = 0;
  492. for (int i = 0; i < num_sections; ++i) {
  493. int64_t section_header_pos = section_table_pos + i * section_header_size;
  494. f->seek(section_header_pos);
  495. uint32_t name_offset = f->get_32();
  496. if (strcmp((char *)strings + name_offset, "pck") == 0) {
  497. if (bits == 32) {
  498. f->seek(section_header_pos + 0x10);
  499. off = f->get_32();
  500. } else { // 64
  501. f->seek(section_header_pos + 0x18);
  502. off = f->get_64();
  503. }
  504. break;
  505. }
  506. }
  507. memfree(strings);
  508. return off;
  509. }
  510. Vector<String> OS_LinuxBSD::get_system_fonts() const {
  511. #ifdef FONTCONFIG_ENABLED
  512. if (!font_config_initialized) {
  513. ERR_FAIL_V_MSG(Vector<String>(), "Unable to load fontconfig, system font support is disabled.");
  514. }
  515. HashSet<String> font_names;
  516. Vector<String> ret;
  517. static const char *allowed_formats[] = { "TrueType", "CFF" };
  518. for (size_t i = 0; i < sizeof(allowed_formats) / sizeof(const char *); i++) {
  519. FcPattern *pattern = FcPatternCreate();
  520. ERR_CONTINUE(!pattern);
  521. FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
  522. FcPatternAddString(pattern, FC_FONTFORMAT, reinterpret_cast<const FcChar8 *>(allowed_formats[i]));
  523. FcFontSet *font_set = FcFontList(config, pattern, object_set);
  524. if (font_set) {
  525. for (int j = 0; j < font_set->nfont; j++) {
  526. char *family_name = nullptr;
  527. if (FcPatternGetString(font_set->fonts[j], FC_FAMILY, 0, reinterpret_cast<FcChar8 **>(&family_name)) == FcResultMatch) {
  528. if (family_name) {
  529. font_names.insert(String::utf8(family_name));
  530. }
  531. }
  532. }
  533. FcFontSetDestroy(font_set);
  534. }
  535. FcPatternDestroy(pattern);
  536. }
  537. for (const String &E : font_names) {
  538. ret.push_back(E);
  539. }
  540. return ret;
  541. #else
  542. ERR_FAIL_V_MSG(Vector<String>(), "Godot was compiled without fontconfig, system font support is disabled.");
  543. #endif
  544. }
  545. #ifdef FONTCONFIG_ENABLED
  546. int OS_LinuxBSD::_weight_to_fc(int p_weight) const {
  547. if (p_weight < 150) {
  548. return FC_WEIGHT_THIN;
  549. } else if (p_weight < 250) {
  550. return FC_WEIGHT_EXTRALIGHT;
  551. } else if (p_weight < 325) {
  552. return FC_WEIGHT_LIGHT;
  553. } else if (p_weight < 375) {
  554. return FC_WEIGHT_DEMILIGHT;
  555. } else if (p_weight < 390) {
  556. return FC_WEIGHT_BOOK;
  557. } else if (p_weight < 450) {
  558. return FC_WEIGHT_REGULAR;
  559. } else if (p_weight < 550) {
  560. return FC_WEIGHT_MEDIUM;
  561. } else if (p_weight < 650) {
  562. return FC_WEIGHT_DEMIBOLD;
  563. } else if (p_weight < 750) {
  564. return FC_WEIGHT_BOLD;
  565. } else if (p_weight < 850) {
  566. return FC_WEIGHT_EXTRABOLD;
  567. } else if (p_weight < 925) {
  568. return FC_WEIGHT_BLACK;
  569. } else {
  570. return FC_WEIGHT_EXTRABLACK;
  571. }
  572. }
  573. int OS_LinuxBSD::_stretch_to_fc(int p_stretch) const {
  574. if (p_stretch < 56) {
  575. return FC_WIDTH_ULTRACONDENSED;
  576. } else if (p_stretch < 69) {
  577. return FC_WIDTH_EXTRACONDENSED;
  578. } else if (p_stretch < 81) {
  579. return FC_WIDTH_CONDENSED;
  580. } else if (p_stretch < 93) {
  581. return FC_WIDTH_SEMICONDENSED;
  582. } else if (p_stretch < 106) {
  583. return FC_WIDTH_NORMAL;
  584. } else if (p_stretch < 137) {
  585. return FC_WIDTH_SEMIEXPANDED;
  586. } else if (p_stretch < 144) {
  587. return FC_WIDTH_EXPANDED;
  588. } else if (p_stretch < 162) {
  589. return FC_WIDTH_EXTRAEXPANDED;
  590. } else {
  591. return FC_WIDTH_ULTRAEXPANDED;
  592. }
  593. }
  594. #endif // FONTCONFIG_ENABLED
  595. 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 {
  596. #ifdef FONTCONFIG_ENABLED
  597. if (!font_config_initialized) {
  598. ERR_FAIL_V_MSG(Vector<String>(), "Unable to load fontconfig, system font support is disabled.");
  599. }
  600. Vector<String> ret;
  601. FcPattern *pattern = FcPatternCreate();
  602. if (pattern) {
  603. FcPatternAddString(pattern, FC_FAMILY, reinterpret_cast<const FcChar8 *>(p_font_name.utf8().get_data()));
  604. FcPatternAddInteger(pattern, FC_WEIGHT, _weight_to_fc(p_weight));
  605. FcPatternAddInteger(pattern, FC_WIDTH, _stretch_to_fc(p_stretch));
  606. FcPatternAddInteger(pattern, FC_SLANT, p_italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN);
  607. FcCharSet *char_set = FcCharSetCreate();
  608. for (int i = 0; i < p_text.size(); i++) {
  609. FcCharSetAddChar(char_set, p_text[i]);
  610. }
  611. FcPatternAddCharSet(pattern, FC_CHARSET, char_set);
  612. FcLangSet *lang_set = FcLangSetCreate();
  613. FcLangSetAdd(lang_set, reinterpret_cast<const FcChar8 *>(p_locale.utf8().get_data()));
  614. FcPatternAddLangSet(pattern, FC_LANG, lang_set);
  615. FcConfigSubstitute(0, pattern, FcMatchPattern);
  616. FcDefaultSubstitute(pattern);
  617. FcResult result;
  618. FcPattern *match = FcFontMatch(0, pattern, &result);
  619. if (match) {
  620. char *file_name = nullptr;
  621. if (FcPatternGetString(match, FC_FILE, 0, reinterpret_cast<FcChar8 **>(&file_name)) == FcResultMatch) {
  622. if (file_name) {
  623. ret.push_back(String::utf8(file_name));
  624. }
  625. }
  626. FcPatternDestroy(match);
  627. }
  628. FcPatternDestroy(pattern);
  629. FcCharSetDestroy(char_set);
  630. FcLangSetDestroy(lang_set);
  631. }
  632. return ret;
  633. #else
  634. ERR_FAIL_V_MSG(Vector<String>(), "Godot was compiled without fontconfig, system font support is disabled.");
  635. #endif
  636. }
  637. String OS_LinuxBSD::get_system_font_path(const String &p_font_name, int p_weight, int p_stretch, bool p_italic) const {
  638. #ifdef FONTCONFIG_ENABLED
  639. if (!font_config_initialized) {
  640. ERR_FAIL_V_MSG(String(), "Unable to load fontconfig, system font support is disabled.");
  641. }
  642. String ret;
  643. FcPattern *pattern = FcPatternCreate();
  644. if (pattern) {
  645. 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");
  646. FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
  647. FcPatternAddString(pattern, FC_FAMILY, reinterpret_cast<const FcChar8 *>(p_font_name.utf8().get_data()));
  648. FcPatternAddInteger(pattern, FC_WEIGHT, _weight_to_fc(p_weight));
  649. FcPatternAddInteger(pattern, FC_WIDTH, _stretch_to_fc(p_stretch));
  650. FcPatternAddInteger(pattern, FC_SLANT, p_italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN);
  651. FcConfigSubstitute(0, pattern, FcMatchPattern);
  652. FcDefaultSubstitute(pattern);
  653. FcResult result;
  654. FcPattern *match = FcFontMatch(0, pattern, &result);
  655. if (match) {
  656. if (!allow_substitutes) {
  657. char *family_name = nullptr;
  658. if (FcPatternGetString(match, FC_FAMILY, 0, reinterpret_cast<FcChar8 **>(&family_name)) == FcResultMatch) {
  659. if (family_name && String::utf8(family_name).to_lower() != p_font_name.to_lower()) {
  660. FcPatternDestroy(match);
  661. FcPatternDestroy(pattern);
  662. return String();
  663. }
  664. }
  665. }
  666. char *file_name = nullptr;
  667. if (FcPatternGetString(match, FC_FILE, 0, reinterpret_cast<FcChar8 **>(&file_name)) == FcResultMatch) {
  668. if (file_name) {
  669. ret = String::utf8(file_name);
  670. }
  671. }
  672. FcPatternDestroy(match);
  673. }
  674. FcPatternDestroy(pattern);
  675. }
  676. return ret;
  677. #else
  678. ERR_FAIL_V_MSG(String(), "Godot was compiled without fontconfig, system font support is disabled.");
  679. #endif
  680. }
  681. String OS_LinuxBSD::get_config_path() const {
  682. if (has_environment("XDG_CONFIG_HOME")) {
  683. if (get_environment("XDG_CONFIG_HOME").is_absolute_path()) {
  684. return get_environment("XDG_CONFIG_HOME");
  685. } else {
  686. 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.");
  687. return has_environment("HOME") ? get_environment("HOME").path_join(".config") : ".";
  688. }
  689. } else if (has_environment("HOME")) {
  690. return get_environment("HOME").path_join(".config");
  691. } else {
  692. return ".";
  693. }
  694. }
  695. String OS_LinuxBSD::get_data_path() const {
  696. if (has_environment("XDG_DATA_HOME")) {
  697. if (get_environment("XDG_DATA_HOME").is_absolute_path()) {
  698. return get_environment("XDG_DATA_HOME");
  699. } else {
  700. 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.");
  701. return has_environment("HOME") ? get_environment("HOME").path_join(".local/share") : get_config_path();
  702. }
  703. } else if (has_environment("HOME")) {
  704. return get_environment("HOME").path_join(".local/share");
  705. } else {
  706. return get_config_path();
  707. }
  708. }
  709. String OS_LinuxBSD::get_cache_path() const {
  710. if (has_environment("XDG_CACHE_HOME")) {
  711. if (get_environment("XDG_CACHE_HOME").is_absolute_path()) {
  712. return get_environment("XDG_CACHE_HOME");
  713. } else {
  714. 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.");
  715. return has_environment("HOME") ? get_environment("HOME").path_join(".cache") : get_config_path();
  716. }
  717. } else if (has_environment("HOME")) {
  718. return get_environment("HOME").path_join(".cache");
  719. } else {
  720. return get_config_path();
  721. }
  722. }
  723. String OS_LinuxBSD::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  724. if (p_dir == SYSTEM_DIR_DESKTOP && !system_dir_desktop_cache.is_empty()) {
  725. return system_dir_desktop_cache;
  726. }
  727. String xdgparam;
  728. switch (p_dir) {
  729. case SYSTEM_DIR_DESKTOP: {
  730. xdgparam = "DESKTOP";
  731. } break;
  732. case SYSTEM_DIR_DCIM: {
  733. xdgparam = "PICTURES";
  734. } break;
  735. case SYSTEM_DIR_DOCUMENTS: {
  736. xdgparam = "DOCUMENTS";
  737. } break;
  738. case SYSTEM_DIR_DOWNLOADS: {
  739. xdgparam = "DOWNLOAD";
  740. } break;
  741. case SYSTEM_DIR_MOVIES: {
  742. xdgparam = "VIDEOS";
  743. } break;
  744. case SYSTEM_DIR_MUSIC: {
  745. xdgparam = "MUSIC";
  746. } break;
  747. case SYSTEM_DIR_PICTURES: {
  748. xdgparam = "PICTURES";
  749. } break;
  750. case SYSTEM_DIR_RINGTONES: {
  751. xdgparam = "MUSIC";
  752. } break;
  753. }
  754. String pipe;
  755. List<String> arg;
  756. arg.push_back(xdgparam);
  757. Error err = const_cast<OS_LinuxBSD *>(this)->execute("xdg-user-dir", arg, &pipe);
  758. if (err != OK) {
  759. return ".";
  760. }
  761. return pipe.strip_edges();
  762. }
  763. void OS_LinuxBSD::run() {
  764. if (!main_loop) {
  765. return;
  766. }
  767. main_loop->initialize();
  768. //uint64_t last_ticks=get_ticks_usec();
  769. //int frames=0;
  770. //uint64_t frame=0;
  771. while (true) {
  772. DisplayServer::get_singleton()->process_events(); // get rid of pending events
  773. #ifdef JOYDEV_ENABLED
  774. joypad->process_joypads();
  775. #endif
  776. if (Main::iteration()) {
  777. break;
  778. }
  779. }
  780. main_loop->finalize();
  781. }
  782. void OS_LinuxBSD::disable_crash_handler() {
  783. crash_handler.disable();
  784. }
  785. bool OS_LinuxBSD::is_disable_crash_handler() const {
  786. return crash_handler.is_disabled();
  787. }
  788. static String get_mountpoint(const String &p_path) {
  789. struct stat s;
  790. if (stat(p_path.utf8().get_data(), &s)) {
  791. return "";
  792. }
  793. #ifdef HAVE_MNTENT
  794. dev_t dev = s.st_dev;
  795. FILE *fd = setmntent("/proc/mounts", "r");
  796. if (!fd) {
  797. return "";
  798. }
  799. struct mntent mnt;
  800. char buf[1024];
  801. size_t buflen = 1024;
  802. while (getmntent_r(fd, &mnt, buf, buflen)) {
  803. if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) {
  804. endmntent(fd);
  805. return String(mnt.mnt_dir);
  806. }
  807. }
  808. endmntent(fd);
  809. #endif
  810. return "";
  811. }
  812. Error OS_LinuxBSD::move_to_trash(const String &p_path) {
  813. String path = p_path.rstrip("/"); // Strip trailing slash when path points to a directory
  814. int err_code;
  815. List<String> args;
  816. args.push_back(path);
  817. args.push_front("trash"); // The command is `gio trash <file_name>` so we need to add it to args.
  818. Error result = execute("gio", args, nullptr, &err_code); // For GNOME based machines.
  819. if (result == OK && !err_code) {
  820. return OK;
  821. } else if (err_code == 2) {
  822. return ERR_FILE_NOT_FOUND;
  823. }
  824. args.pop_front();
  825. args.push_front("move");
  826. args.push_back("trash:/"); // The command is `kioclient5 move <file_name> trash:/`.
  827. result = execute("kioclient5", args, nullptr, &err_code); // For KDE based machines.
  828. if (result == OK && !err_code) {
  829. return OK;
  830. } else if (err_code == 2) {
  831. return ERR_FILE_NOT_FOUND;
  832. }
  833. args.pop_front();
  834. args.pop_back();
  835. result = execute("gvfs-trash", args, nullptr, &err_code); // For older Linux machines.
  836. if (result == OK && !err_code) {
  837. return OK;
  838. } else if (err_code == 2) {
  839. return ERR_FILE_NOT_FOUND;
  840. }
  841. // If the commands `kioclient5`, `gio` or `gvfs-trash` don't exist on the system we do it manually.
  842. String trash_path = "";
  843. String mnt = get_mountpoint(path);
  844. // If there is a directory "[Mountpoint]/.Trash-[UID], use it as the trash can.
  845. if (!mnt.is_empty()) {
  846. String mountpoint_trash_path(mnt + "/.Trash-" + itos(getuid()));
  847. struct stat s;
  848. if (!stat(mountpoint_trash_path.utf8().get_data(), &s)) {
  849. trash_path = mountpoint_trash_path;
  850. }
  851. }
  852. // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash" as the trash can.
  853. if (trash_path.is_empty()) {
  854. char *dhome = getenv("XDG_DATA_HOME");
  855. if (dhome) {
  856. trash_path = String::utf8(dhome) + "/Trash";
  857. }
  858. }
  859. // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash" as the trash can.
  860. if (trash_path.is_empty()) {
  861. char *home = getenv("HOME");
  862. if (home) {
  863. trash_path = String::utf8(home) + "/.local/share/Trash";
  864. }
  865. }
  866. // Issue an error if none of the previous locations is appropriate for the trash can.
  867. ERR_FAIL_COND_V_MSG(trash_path.is_empty(), FAILED, "Could not determine the trash can location");
  868. // Create needed directories for decided trash can location.
  869. {
  870. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  871. Error err = dir_access->make_dir_recursive(trash_path);
  872. // Issue an error if trash can is not created properly.
  873. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"");
  874. err = dir_access->make_dir_recursive(trash_path + "/files");
  875. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/files\"");
  876. err = dir_access->make_dir_recursive(trash_path + "/info");
  877. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/info\"");
  878. }
  879. // The trash can is successfully created, now we check that we don't exceed our file name length limit.
  880. // If the file name is too long trim it so we can add the identifying number and ".trashinfo".
  881. // Assumes that the file name length limit is 255 characters.
  882. String file_name = path.get_file();
  883. if (file_name.length() > 240) {
  884. file_name = file_name.substr(0, file_name.length() - 15);
  885. }
  886. String dest_path = trash_path + "/files/" + file_name;
  887. struct stat buff;
  888. int id_number = 0;
  889. String fn = file_name;
  890. // Checks if a resource with the same name already exist in the trash can,
  891. // if there is, add an identifying number to our resource's name.
  892. while (stat(dest_path.utf8().get_data(), &buff) == 0) {
  893. id_number++;
  894. // Added a limit to check for identically named files already on the trash can
  895. // if there are too many it could make the editor unresponsive.
  896. ERR_FAIL_COND_V_MSG(id_number > 99, FAILED, "Too many identically named resources already in the trash can.");
  897. fn = file_name + "." + itos(id_number);
  898. dest_path = trash_path + "/files/" + fn;
  899. }
  900. file_name = fn;
  901. String renamed_path = path.get_base_dir() + "/" + file_name;
  902. // Generates the .trashinfo file
  903. OS::DateTime dt = OS::get_singleton()->get_datetime(false);
  904. String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", dt.year, (int)dt.month, dt.day, dt.hour, dt.minute);
  905. timestamp = vformat("%s%02d", timestamp, dt.second); // vformat only supports up to 6 arguments.
  906. String trash_info = "[Trash Info]\nPath=" + path.uri_encode() + "\nDeletionDate=" + timestamp + "\n";
  907. {
  908. Error err;
  909. {
  910. Ref<FileAccess> file = FileAccess::open(trash_path + "/info/" + file_name + ".trashinfo", FileAccess::WRITE, &err);
  911. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't create trashinfo file: \"" + trash_path + "/info/" + file_name + ".trashinfo\"");
  912. file->store_string(trash_info);
  913. }
  914. // Rename our resource before moving it to the trash can.
  915. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  916. err = dir_access->rename(path, renamed_path);
  917. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't rename file \"" + path + "\" to \"" + renamed_path + "\"");
  918. }
  919. // Move the given resource to the trash can.
  920. // Do not use DirAccess:rename() because it can't move files across multiple mountpoints.
  921. List<String> mv_args;
  922. mv_args.push_back(renamed_path);
  923. mv_args.push_back(trash_path + "/files");
  924. {
  925. int retval;
  926. Error err = execute("mv", mv_args, nullptr, &retval);
  927. // Issue an error if "mv" failed to move the given resource to the trash can.
  928. if (err != OK || retval != 0) {
  929. ERR_PRINT("move_to_trash: Could not move the resource \"" + path + "\" to the trash can \"" + trash_path + "/files\"");
  930. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  931. err = dir_access->rename(renamed_path, path);
  932. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not rename \"" + renamed_path + "\" back to its original name: \"" + path + "\"");
  933. return FAILED;
  934. }
  935. }
  936. return OK;
  937. }
  938. OS_LinuxBSD::OS_LinuxBSD() {
  939. main_loop = nullptr;
  940. #ifdef PULSEAUDIO_ENABLED
  941. AudioDriverManager::add_driver(&driver_pulseaudio);
  942. #endif
  943. #ifdef ALSA_ENABLED
  944. AudioDriverManager::add_driver(&driver_alsa);
  945. #endif
  946. #ifdef X11_ENABLED
  947. DisplayServerX11::register_x11_driver();
  948. #endif
  949. #ifdef FONTCONFIG_ENABLED
  950. #ifdef DEBUG_ENABLED
  951. int dylibloader_verbose = 1;
  952. #else
  953. int dylibloader_verbose = 0;
  954. #endif
  955. font_config_initialized = (initialize_fontconfig(dylibloader_verbose) == 0);
  956. if (font_config_initialized) {
  957. config = FcInitLoadConfigAndFonts();
  958. if (!config) {
  959. font_config_initialized = false;
  960. }
  961. object_set = FcObjectSetBuild(FC_FAMILY, FC_FILE, nullptr);
  962. if (!object_set) {
  963. font_config_initialized = false;
  964. }
  965. }
  966. #endif // FONTCONFIG_ENABLED
  967. }
  968. OS_LinuxBSD::~OS_LinuxBSD() {
  969. #ifdef FONTCONFIG_ENABLED
  970. if (object_set) {
  971. FcObjectSetDestroy(object_set);
  972. }
  973. if (config) {
  974. FcConfigDestroy(config);
  975. }
  976. #endif // FONTCONFIG_ENABLED
  977. }