os_linuxbsd.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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. #ifdef FONTCONFIG_ENABLED
  544. int OS_LinuxBSD::_weight_to_fc(int p_weight) const {
  545. if (p_weight < 150) {
  546. return FC_WEIGHT_THIN;
  547. } else if (p_weight < 250) {
  548. return FC_WEIGHT_EXTRALIGHT;
  549. } else if (p_weight < 325) {
  550. return FC_WEIGHT_LIGHT;
  551. } else if (p_weight < 375) {
  552. return FC_WEIGHT_DEMILIGHT;
  553. } else if (p_weight < 390) {
  554. return FC_WEIGHT_BOOK;
  555. } else if (p_weight < 450) {
  556. return FC_WEIGHT_REGULAR;
  557. } else if (p_weight < 550) {
  558. return FC_WEIGHT_MEDIUM;
  559. } else if (p_weight < 650) {
  560. return FC_WEIGHT_DEMIBOLD;
  561. } else if (p_weight < 750) {
  562. return FC_WEIGHT_BOLD;
  563. } else if (p_weight < 850) {
  564. return FC_WEIGHT_EXTRABOLD;
  565. } else if (p_weight < 925) {
  566. return FC_WEIGHT_BLACK;
  567. } else {
  568. return FC_WEIGHT_EXTRABLACK;
  569. }
  570. }
  571. int OS_LinuxBSD::_stretch_to_fc(int p_stretch) const {
  572. if (p_stretch < 56) {
  573. return FC_WIDTH_ULTRACONDENSED;
  574. } else if (p_stretch < 69) {
  575. return FC_WIDTH_EXTRACONDENSED;
  576. } else if (p_stretch < 81) {
  577. return FC_WIDTH_CONDENSED;
  578. } else if (p_stretch < 93) {
  579. return FC_WIDTH_SEMICONDENSED;
  580. } else if (p_stretch < 106) {
  581. return FC_WIDTH_NORMAL;
  582. } else if (p_stretch < 137) {
  583. return FC_WIDTH_SEMIEXPANDED;
  584. } else if (p_stretch < 144) {
  585. return FC_WIDTH_EXPANDED;
  586. } else if (p_stretch < 162) {
  587. return FC_WIDTH_EXTRAEXPANDED;
  588. } else {
  589. return FC_WIDTH_ULTRAEXPANDED;
  590. }
  591. }
  592. #endif // FONTCONFIG_ENABLED
  593. 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 {
  594. #ifdef FONTCONFIG_ENABLED
  595. if (!font_config_initialized) {
  596. ERR_FAIL_V_MSG(Vector<String>(), "Unable to load fontconfig, system font support is disabled.");
  597. }
  598. Vector<String> ret;
  599. FcPattern *pattern = FcPatternCreate();
  600. if (pattern) {
  601. FcPatternAddString(pattern, FC_FAMILY, reinterpret_cast<const FcChar8 *>(p_font_name.utf8().get_data()));
  602. FcPatternAddInteger(pattern, FC_WEIGHT, _weight_to_fc(p_weight));
  603. FcPatternAddInteger(pattern, FC_WIDTH, _stretch_to_fc(p_stretch));
  604. FcPatternAddInteger(pattern, FC_SLANT, p_italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN);
  605. FcCharSet *char_set = FcCharSetCreate();
  606. for (int i = 0; i < p_text.size(); i++) {
  607. FcCharSetAddChar(char_set, p_text[i]);
  608. }
  609. FcPatternAddCharSet(pattern, FC_CHARSET, char_set);
  610. FcLangSet *lang_set = FcLangSetCreate();
  611. FcLangSetAdd(lang_set, reinterpret_cast<const FcChar8 *>(p_locale.utf8().get_data()));
  612. FcPatternAddLangSet(pattern, FC_LANG, lang_set);
  613. FcConfigSubstitute(0, pattern, FcMatchPattern);
  614. FcDefaultSubstitute(pattern);
  615. FcResult result;
  616. FcPattern *match = FcFontMatch(0, pattern, &result);
  617. if (match) {
  618. char *file_name = nullptr;
  619. if (FcPatternGetString(match, FC_FILE, 0, reinterpret_cast<FcChar8 **>(&file_name)) == FcResultMatch) {
  620. if (file_name) {
  621. ret.push_back(String::utf8(file_name));
  622. }
  623. }
  624. FcPatternDestroy(match);
  625. }
  626. FcPatternDestroy(pattern);
  627. FcCharSetDestroy(char_set);
  628. FcLangSetDestroy(lang_set);
  629. }
  630. return ret;
  631. #else
  632. ERR_FAIL_V_MSG(Vector<String>(), "Godot was compiled without fontconfig, system font support is disabled.");
  633. #endif
  634. }
  635. String OS_LinuxBSD::get_system_font_path(const String &p_font_name, int p_weight, int p_stretch, bool p_italic) const {
  636. #ifdef FONTCONFIG_ENABLED
  637. if (!font_config_initialized) {
  638. ERR_FAIL_V_MSG(String(), "Unable to load fontconfig, system font support is disabled.");
  639. }
  640. String ret;
  641. FcPattern *pattern = FcPatternCreate();
  642. if (pattern) {
  643. 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");
  644. FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
  645. FcPatternAddString(pattern, FC_FAMILY, reinterpret_cast<const FcChar8 *>(p_font_name.utf8().get_data()));
  646. FcPatternAddInteger(pattern, FC_WEIGHT, _weight_to_fc(p_weight));
  647. FcPatternAddInteger(pattern, FC_WIDTH, _stretch_to_fc(p_stretch));
  648. FcPatternAddInteger(pattern, FC_SLANT, p_italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN);
  649. FcConfigSubstitute(0, pattern, FcMatchPattern);
  650. FcDefaultSubstitute(pattern);
  651. FcResult result;
  652. FcPattern *match = FcFontMatch(0, pattern, &result);
  653. if (match) {
  654. if (!allow_substitutes) {
  655. char *family_name = nullptr;
  656. if (FcPatternGetString(match, FC_FAMILY, 0, reinterpret_cast<FcChar8 **>(&family_name)) == FcResultMatch) {
  657. if (family_name && String::utf8(family_name).to_lower() != p_font_name.to_lower()) {
  658. FcPatternDestroy(match);
  659. FcPatternDestroy(pattern);
  660. return String();
  661. }
  662. }
  663. }
  664. char *file_name = nullptr;
  665. if (FcPatternGetString(match, FC_FILE, 0, reinterpret_cast<FcChar8 **>(&file_name)) == FcResultMatch) {
  666. if (file_name) {
  667. ret = String::utf8(file_name);
  668. }
  669. }
  670. FcPatternDestroy(match);
  671. }
  672. FcPatternDestroy(pattern);
  673. }
  674. return ret;
  675. #else
  676. ERR_FAIL_V_MSG(String(), "Godot was compiled without fontconfig, system font support is disabled.");
  677. #endif
  678. }
  679. String OS_LinuxBSD::get_config_path() const {
  680. if (has_environment("XDG_CONFIG_HOME")) {
  681. if (get_environment("XDG_CONFIG_HOME").is_absolute_path()) {
  682. return get_environment("XDG_CONFIG_HOME");
  683. } else {
  684. 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.");
  685. return has_environment("HOME") ? get_environment("HOME").path_join(".config") : ".";
  686. }
  687. } else if (has_environment("HOME")) {
  688. return get_environment("HOME").path_join(".config");
  689. } else {
  690. return ".";
  691. }
  692. }
  693. String OS_LinuxBSD::get_data_path() const {
  694. if (has_environment("XDG_DATA_HOME")) {
  695. if (get_environment("XDG_DATA_HOME").is_absolute_path()) {
  696. return get_environment("XDG_DATA_HOME");
  697. } else {
  698. 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.");
  699. return has_environment("HOME") ? get_environment("HOME").path_join(".local/share") : get_config_path();
  700. }
  701. } else if (has_environment("HOME")) {
  702. return get_environment("HOME").path_join(".local/share");
  703. } else {
  704. return get_config_path();
  705. }
  706. }
  707. String OS_LinuxBSD::get_cache_path() const {
  708. if (has_environment("XDG_CACHE_HOME")) {
  709. if (get_environment("XDG_CACHE_HOME").is_absolute_path()) {
  710. return get_environment("XDG_CACHE_HOME");
  711. } else {
  712. 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.");
  713. return has_environment("HOME") ? get_environment("HOME").path_join(".cache") : get_config_path();
  714. }
  715. } else if (has_environment("HOME")) {
  716. return get_environment("HOME").path_join(".cache");
  717. } else {
  718. return get_config_path();
  719. }
  720. }
  721. String OS_LinuxBSD::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  722. if (p_dir == SYSTEM_DIR_DESKTOP && !system_dir_desktop_cache.is_empty()) {
  723. return system_dir_desktop_cache;
  724. }
  725. String xdgparam;
  726. switch (p_dir) {
  727. case SYSTEM_DIR_DESKTOP: {
  728. xdgparam = "DESKTOP";
  729. } break;
  730. case SYSTEM_DIR_DCIM: {
  731. xdgparam = "PICTURES";
  732. } break;
  733. case SYSTEM_DIR_DOCUMENTS: {
  734. xdgparam = "DOCUMENTS";
  735. } break;
  736. case SYSTEM_DIR_DOWNLOADS: {
  737. xdgparam = "DOWNLOAD";
  738. } break;
  739. case SYSTEM_DIR_MOVIES: {
  740. xdgparam = "VIDEOS";
  741. } break;
  742. case SYSTEM_DIR_MUSIC: {
  743. xdgparam = "MUSIC";
  744. } break;
  745. case SYSTEM_DIR_PICTURES: {
  746. xdgparam = "PICTURES";
  747. } break;
  748. case SYSTEM_DIR_RINGTONES: {
  749. xdgparam = "MUSIC";
  750. } break;
  751. }
  752. String pipe;
  753. List<String> arg;
  754. arg.push_back(xdgparam);
  755. Error err = const_cast<OS_LinuxBSD *>(this)->execute("xdg-user-dir", arg, &pipe);
  756. if (err != OK) {
  757. return ".";
  758. }
  759. return pipe.strip_edges();
  760. }
  761. void OS_LinuxBSD::run() {
  762. if (!main_loop) {
  763. return;
  764. }
  765. main_loop->initialize();
  766. //uint64_t last_ticks=get_ticks_usec();
  767. //int frames=0;
  768. //uint64_t frame=0;
  769. while (true) {
  770. DisplayServer::get_singleton()->process_events(); // get rid of pending events
  771. #ifdef JOYDEV_ENABLED
  772. joypad->process_joypads();
  773. #endif
  774. if (Main::iteration()) {
  775. break;
  776. }
  777. }
  778. main_loop->finalize();
  779. }
  780. void OS_LinuxBSD::disable_crash_handler() {
  781. crash_handler.disable();
  782. }
  783. bool OS_LinuxBSD::is_disable_crash_handler() const {
  784. return crash_handler.is_disabled();
  785. }
  786. static String get_mountpoint(const String &p_path) {
  787. struct stat s;
  788. if (stat(p_path.utf8().get_data(), &s)) {
  789. return "";
  790. }
  791. #ifdef HAVE_MNTENT
  792. dev_t dev = s.st_dev;
  793. FILE *fd = setmntent("/proc/mounts", "r");
  794. if (!fd) {
  795. return "";
  796. }
  797. struct mntent mnt;
  798. char buf[1024];
  799. size_t buflen = 1024;
  800. while (getmntent_r(fd, &mnt, buf, buflen)) {
  801. if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) {
  802. endmntent(fd);
  803. return String(mnt.mnt_dir);
  804. }
  805. }
  806. endmntent(fd);
  807. #endif
  808. return "";
  809. }
  810. Error OS_LinuxBSD::move_to_trash(const String &p_path) {
  811. String path = p_path.rstrip("/"); // Strip trailing slash when path points to a directory
  812. int err_code;
  813. List<String> args;
  814. args.push_back(path);
  815. args.push_front("trash"); // The command is `gio trash <file_name>` so we need to add it to args.
  816. Error result = execute("gio", args, nullptr, &err_code); // For GNOME based machines.
  817. if (result == OK && !err_code) {
  818. return OK;
  819. } else if (err_code == 2) {
  820. return ERR_FILE_NOT_FOUND;
  821. }
  822. args.pop_front();
  823. args.push_front("move");
  824. args.push_back("trash:/"); // The command is `kioclient5 move <file_name> trash:/`.
  825. result = execute("kioclient5", args, nullptr, &err_code); // For KDE based machines.
  826. if (result == OK && !err_code) {
  827. return OK;
  828. } else if (err_code == 2) {
  829. return ERR_FILE_NOT_FOUND;
  830. }
  831. args.pop_front();
  832. args.pop_back();
  833. result = execute("gvfs-trash", args, nullptr, &err_code); // For older Linux machines.
  834. if (result == OK && !err_code) {
  835. return OK;
  836. } else if (err_code == 2) {
  837. return ERR_FILE_NOT_FOUND;
  838. }
  839. // If the commands `kioclient5`, `gio` or `gvfs-trash` don't exist on the system we do it manually.
  840. String trash_path = "";
  841. String mnt = get_mountpoint(path);
  842. // If there is a directory "[Mountpoint]/.Trash-[UID], use it as the trash can.
  843. if (!mnt.is_empty()) {
  844. String mountpoint_trash_path(mnt + "/.Trash-" + itos(getuid()));
  845. struct stat s;
  846. if (!stat(mountpoint_trash_path.utf8().get_data(), &s)) {
  847. trash_path = mountpoint_trash_path;
  848. }
  849. }
  850. // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash" as the trash can.
  851. if (trash_path.is_empty()) {
  852. char *dhome = getenv("XDG_DATA_HOME");
  853. if (dhome) {
  854. trash_path = String::utf8(dhome) + "/Trash";
  855. }
  856. }
  857. // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash" as the trash can.
  858. if (trash_path.is_empty()) {
  859. char *home = getenv("HOME");
  860. if (home) {
  861. trash_path = String::utf8(home) + "/.local/share/Trash";
  862. }
  863. }
  864. // Issue an error if none of the previous locations is appropriate for the trash can.
  865. ERR_FAIL_COND_V_MSG(trash_path.is_empty(), FAILED, "Could not determine the trash can location");
  866. // Create needed directories for decided trash can location.
  867. {
  868. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  869. Error err = dir_access->make_dir_recursive(trash_path);
  870. // Issue an error if trash can is not created properly.
  871. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"");
  872. err = dir_access->make_dir_recursive(trash_path + "/files");
  873. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/files\"");
  874. err = dir_access->make_dir_recursive(trash_path + "/info");
  875. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/info\"");
  876. }
  877. // The trash can is successfully created, now we check that we don't exceed our file name length limit.
  878. // If the file name is too long trim it so we can add the identifying number and ".trashinfo".
  879. // Assumes that the file name length limit is 255 characters.
  880. String file_name = path.get_file();
  881. if (file_name.length() > 240) {
  882. file_name = file_name.substr(0, file_name.length() - 15);
  883. }
  884. String dest_path = trash_path + "/files/" + file_name;
  885. struct stat buff;
  886. int id_number = 0;
  887. String fn = file_name;
  888. // Checks if a resource with the same name already exist in the trash can,
  889. // if there is, add an identifying number to our resource's name.
  890. while (stat(dest_path.utf8().get_data(), &buff) == 0) {
  891. id_number++;
  892. // Added a limit to check for identically named files already on the trash can
  893. // if there are too many it could make the editor unresponsive.
  894. ERR_FAIL_COND_V_MSG(id_number > 99, FAILED, "Too many identically named resources already in the trash can.");
  895. fn = file_name + "." + itos(id_number);
  896. dest_path = trash_path + "/files/" + fn;
  897. }
  898. file_name = fn;
  899. String renamed_path = path.get_base_dir() + "/" + file_name;
  900. // Generates the .trashinfo file
  901. OS::DateTime dt = OS::get_singleton()->get_datetime(false);
  902. String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", dt.year, (int)dt.month, dt.day, dt.hour, dt.minute);
  903. timestamp = vformat("%s%02d", timestamp, dt.second); // vformat only supports up to 6 arguments.
  904. String trash_info = "[Trash Info]\nPath=" + path.uri_encode() + "\nDeletionDate=" + timestamp + "\n";
  905. {
  906. Error err;
  907. {
  908. Ref<FileAccess> file = FileAccess::open(trash_path + "/info/" + file_name + ".trashinfo", FileAccess::WRITE, &err);
  909. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't create trashinfo file: \"" + trash_path + "/info/" + file_name + ".trashinfo\"");
  910. file->store_string(trash_info);
  911. }
  912. // Rename our resource before moving it to the trash can.
  913. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  914. err = dir_access->rename(path, renamed_path);
  915. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't rename file \"" + path + "\" to \"" + renamed_path + "\"");
  916. }
  917. // Move the given resource to the trash can.
  918. // Do not use DirAccess:rename() because it can't move files across multiple mountpoints.
  919. List<String> mv_args;
  920. mv_args.push_back(renamed_path);
  921. mv_args.push_back(trash_path + "/files");
  922. {
  923. int retval;
  924. Error err = execute("mv", mv_args, nullptr, &retval);
  925. // Issue an error if "mv" failed to move the given resource to the trash can.
  926. if (err != OK || retval != 0) {
  927. ERR_PRINT("move_to_trash: Could not move the resource \"" + path + "\" to the trash can \"" + trash_path + "/files\"");
  928. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  929. err = dir_access->rename(renamed_path, path);
  930. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not rename \"" + renamed_path + "\" back to its original name: \"" + path + "\"");
  931. return FAILED;
  932. }
  933. }
  934. return OK;
  935. }
  936. OS_LinuxBSD::OS_LinuxBSD() {
  937. main_loop = nullptr;
  938. #ifdef PULSEAUDIO_ENABLED
  939. AudioDriverManager::add_driver(&driver_pulseaudio);
  940. #endif
  941. #ifdef ALSA_ENABLED
  942. AudioDriverManager::add_driver(&driver_alsa);
  943. #endif
  944. #ifdef X11_ENABLED
  945. DisplayServerX11::register_x11_driver();
  946. #endif
  947. #ifdef FONTCONFIG_ENABLED
  948. #ifdef DEBUG_ENABLED
  949. int dylibloader_verbose = 1;
  950. #else
  951. int dylibloader_verbose = 0;
  952. #endif
  953. font_config_initialized = (initialize_fontconfig(dylibloader_verbose) == 0);
  954. if (font_config_initialized) {
  955. config = FcInitLoadConfigAndFonts();
  956. if (!config) {
  957. font_config_initialized = false;
  958. }
  959. object_set = FcObjectSetBuild(FC_FAMILY, FC_FILE, nullptr);
  960. if (!object_set) {
  961. font_config_initialized = false;
  962. }
  963. }
  964. #endif // FONTCONFIG_ENABLED
  965. }
  966. OS_LinuxBSD::~OS_LinuxBSD() {
  967. #ifdef FONTCONFIG_ENABLED
  968. if (object_set) {
  969. FcObjectSetDestroy(object_set);
  970. }
  971. if (config) {
  972. FcConfigDestroy(config);
  973. }
  974. #endif // FONTCONFIG_ENABLED
  975. }