os_linuxbsd.cpp 35 KB

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