os_linuxbsd.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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. #ifdef X11_ENABLED
  35. #include "display_server_x11.h"
  36. #endif
  37. #ifdef HAVE_MNTENT
  38. #include <mntent.h>
  39. #endif
  40. #include <dlfcn.h>
  41. #include <stdio.h>
  42. #include <stdlib.h>
  43. #include <string.h>
  44. #include <sys/stat.h>
  45. #include <sys/types.h>
  46. #include <sys/utsname.h>
  47. #include <unistd.h>
  48. #ifdef FONTCONFIG_ENABLED
  49. #include "fontconfig-so_wrap.h"
  50. #endif
  51. void OS_LinuxBSD::alert(const String &p_alert, const String &p_title) {
  52. const char *message_programs[] = { "zenity", "kdialog", "Xdialog", "xmessage" };
  53. String path = get_environment("PATH");
  54. Vector<String> path_elems = path.split(":", false);
  55. String program;
  56. for (int i = 0; i < path_elems.size(); i++) {
  57. for (uint64_t k = 0; k < sizeof(message_programs) / sizeof(char *); k++) {
  58. String tested_path = path_elems[i].path_join(message_programs[k]);
  59. if (FileAccess::exists(tested_path)) {
  60. program = tested_path;
  61. break;
  62. }
  63. }
  64. if (program.length()) {
  65. break;
  66. }
  67. }
  68. List<String> args;
  69. if (program.ends_with("zenity")) {
  70. args.push_back("--error");
  71. args.push_back("--width");
  72. args.push_back("500");
  73. args.push_back("--title");
  74. args.push_back(p_title);
  75. args.push_back("--text");
  76. args.push_back(p_alert);
  77. }
  78. if (program.ends_with("kdialog")) {
  79. args.push_back("--error");
  80. args.push_back(p_alert);
  81. args.push_back("--title");
  82. args.push_back(p_title);
  83. }
  84. if (program.ends_with("Xdialog")) {
  85. args.push_back("--title");
  86. args.push_back(p_title);
  87. args.push_back("--msgbox");
  88. args.push_back(p_alert);
  89. args.push_back("0");
  90. args.push_back("0");
  91. }
  92. if (program.ends_with("xmessage")) {
  93. args.push_back("-center");
  94. args.push_back("-title");
  95. args.push_back(p_title);
  96. args.push_back(p_alert);
  97. }
  98. if (program.length()) {
  99. execute(program, args);
  100. } else {
  101. print_line(p_alert);
  102. }
  103. }
  104. void OS_LinuxBSD::initialize() {
  105. crash_handler.initialize();
  106. OS_Unix::initialize_core();
  107. }
  108. void OS_LinuxBSD::initialize_joypads() {
  109. #ifdef JOYDEV_ENABLED
  110. joypad = memnew(JoypadLinux(Input::get_singleton()));
  111. #endif
  112. }
  113. String OS_LinuxBSD::get_unique_id() const {
  114. static String machine_id;
  115. if (machine_id.is_empty()) {
  116. Ref<FileAccess> f = FileAccess::open("/etc/machine-id", FileAccess::READ);
  117. if (f.is_valid()) {
  118. while (machine_id.is_empty() && !f->eof_reached()) {
  119. machine_id = f->get_line().strip_edges();
  120. }
  121. }
  122. }
  123. return machine_id;
  124. }
  125. String OS_LinuxBSD::get_processor_name() const {
  126. Ref<FileAccess> f = FileAccess::open("/proc/cpuinfo", FileAccess::READ);
  127. ERR_FAIL_COND_V_MSG(f.is_null(), "", String("Couldn't open `/proc/cpuinfo` to get the CPU model name. Returning an empty string."));
  128. while (!f->eof_reached()) {
  129. const String line = f->get_line();
  130. if (line.find("model name") != -1) {
  131. return line.split(":")[1].strip_edges();
  132. }
  133. }
  134. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name from `/proc/cpuinfo`. Returning an empty string."));
  135. }
  136. void OS_LinuxBSD::finalize() {
  137. if (main_loop) {
  138. memdelete(main_loop);
  139. }
  140. main_loop = nullptr;
  141. #ifdef ALSAMIDI_ENABLED
  142. driver_alsamidi.close();
  143. #endif
  144. #ifdef JOYDEV_ENABLED
  145. if (joypad) {
  146. memdelete(joypad);
  147. }
  148. #endif
  149. }
  150. MainLoop *OS_LinuxBSD::get_main_loop() const {
  151. return main_loop;
  152. }
  153. void OS_LinuxBSD::delete_main_loop() {
  154. if (main_loop) {
  155. memdelete(main_loop);
  156. }
  157. main_loop = nullptr;
  158. }
  159. void OS_LinuxBSD::set_main_loop(MainLoop *p_main_loop) {
  160. main_loop = p_main_loop;
  161. }
  162. String OS_LinuxBSD::get_name() const {
  163. #ifdef __linux__
  164. return "Linux";
  165. #elif defined(__FreeBSD__)
  166. return "FreeBSD";
  167. #elif defined(__NetBSD__)
  168. return "NetBSD";
  169. #elif defined(__OpenBSD__)
  170. return "OpenBSD";
  171. #else
  172. return "BSD";
  173. #endif
  174. }
  175. String OS_LinuxBSD::get_systemd_os_release_info_value(const String &key) const {
  176. static String info;
  177. if (info.is_empty()) {
  178. Ref<FileAccess> f = FileAccess::open("/etc/os-release", FileAccess::READ);
  179. if (f.is_valid()) {
  180. while (!f->eof_reached()) {
  181. const String line = f->get_line();
  182. if (line.find(key) != -1) {
  183. return line.split("=")[1].strip_edges();
  184. }
  185. }
  186. }
  187. }
  188. return info;
  189. }
  190. String OS_LinuxBSD::get_distribution_name() const {
  191. static String systemd_name = get_systemd_os_release_info_value("NAME"); // returns a value for systemd users, otherwise an empty string.
  192. if (!systemd_name.is_empty()) {
  193. return systemd_name;
  194. }
  195. struct utsname uts; // returns a decent value for BSD family.
  196. uname(&uts);
  197. return uts.sysname;
  198. }
  199. String OS_LinuxBSD::get_version() const {
  200. static String systemd_version = get_systemd_os_release_info_value("VERSION"); // returns a value for systemd users, otherwise an empty string.
  201. if (!systemd_version.is_empty()) {
  202. return systemd_version;
  203. }
  204. struct utsname uts; // returns a decent value for BSD family.
  205. uname(&uts);
  206. return uts.version;
  207. }
  208. Error OS_LinuxBSD::shell_open(String p_uri) {
  209. Error ok;
  210. int err_code;
  211. List<String> args;
  212. args.push_back(p_uri);
  213. // Agnostic
  214. ok = execute("xdg-open", args, nullptr, &err_code);
  215. if (ok == OK && !err_code) {
  216. return OK;
  217. } else if (err_code == 2) {
  218. return ERR_FILE_NOT_FOUND;
  219. }
  220. // GNOME
  221. args.push_front("open"); // The command is `gio open`, so we need to add it to args
  222. ok = execute("gio", args, nullptr, &err_code);
  223. if (ok == OK && !err_code) {
  224. return OK;
  225. } else if (err_code == 2) {
  226. return ERR_FILE_NOT_FOUND;
  227. }
  228. args.pop_front();
  229. ok = execute("gvfs-open", args, nullptr, &err_code);
  230. if (ok == OK && !err_code) {
  231. return OK;
  232. } else if (err_code == 2) {
  233. return ERR_FILE_NOT_FOUND;
  234. }
  235. // KDE
  236. ok = execute("kde-open5", args, nullptr, &err_code);
  237. if (ok == OK && !err_code) {
  238. return OK;
  239. }
  240. ok = execute("kde-open", args, nullptr, &err_code);
  241. return !err_code ? ok : FAILED;
  242. }
  243. bool OS_LinuxBSD::_check_internal_feature_support(const String &p_feature) {
  244. return p_feature == "pc";
  245. }
  246. uint64_t OS_LinuxBSD::get_embedded_pck_offset() const {
  247. Ref<FileAccess> f = FileAccess::open(get_executable_path(), FileAccess::READ);
  248. if (f.is_null()) {
  249. return 0;
  250. }
  251. // Read and check ELF magic number.
  252. {
  253. uint32_t magic = f->get_32();
  254. if (magic != 0x464c457f) { // 0x7F + "ELF"
  255. return 0;
  256. }
  257. }
  258. // Read program architecture bits from class field.
  259. int bits = f->get_8() * 32;
  260. // Get info about the section header table.
  261. int64_t section_table_pos;
  262. int64_t section_header_size;
  263. if (bits == 32) {
  264. section_header_size = 40;
  265. f->seek(0x20);
  266. section_table_pos = f->get_32();
  267. f->seek(0x30);
  268. } else { // 64
  269. section_header_size = 64;
  270. f->seek(0x28);
  271. section_table_pos = f->get_64();
  272. f->seek(0x3c);
  273. }
  274. int num_sections = f->get_16();
  275. int string_section_idx = f->get_16();
  276. // Load the strings table.
  277. uint8_t *strings;
  278. {
  279. // Jump to the strings section header.
  280. f->seek(section_table_pos + string_section_idx * section_header_size);
  281. // Read strings data size and offset.
  282. int64_t string_data_pos;
  283. int64_t string_data_size;
  284. if (bits == 32) {
  285. f->seek(f->get_position() + 0x10);
  286. string_data_pos = f->get_32();
  287. string_data_size = f->get_32();
  288. } else { // 64
  289. f->seek(f->get_position() + 0x18);
  290. string_data_pos = f->get_64();
  291. string_data_size = f->get_64();
  292. }
  293. // Read strings data.
  294. f->seek(string_data_pos);
  295. strings = (uint8_t *)memalloc(string_data_size);
  296. if (!strings) {
  297. return 0;
  298. }
  299. f->get_buffer(strings, string_data_size);
  300. }
  301. // Search for the "pck" section.
  302. int64_t off = 0;
  303. for (int i = 0; i < num_sections; ++i) {
  304. int64_t section_header_pos = section_table_pos + i * section_header_size;
  305. f->seek(section_header_pos);
  306. uint32_t name_offset = f->get_32();
  307. if (strcmp((char *)strings + name_offset, "pck") == 0) {
  308. if (bits == 32) {
  309. f->seek(section_header_pos + 0x10);
  310. off = f->get_32();
  311. } else { // 64
  312. f->seek(section_header_pos + 0x18);
  313. off = f->get_64();
  314. }
  315. break;
  316. }
  317. }
  318. memfree(strings);
  319. return off;
  320. }
  321. Vector<String> OS_LinuxBSD::get_system_fonts() const {
  322. #ifdef FONTCONFIG_ENABLED
  323. if (!font_config_initialized) {
  324. ERR_FAIL_V_MSG(Vector<String>(), "Unable to load fontconfig, system font support is disabled.");
  325. }
  326. HashSet<String> font_names;
  327. Vector<String> ret;
  328. FcConfig *config = FcInitLoadConfigAndFonts();
  329. ERR_FAIL_COND_V(!config, ret);
  330. FcObjectSet *object_set = FcObjectSetBuild(FC_FAMILY, nullptr);
  331. ERR_FAIL_COND_V(!object_set, ret);
  332. static const char *allowed_formats[] = { "TrueType", "CFF" };
  333. for (size_t i = 0; i < sizeof(allowed_formats) / sizeof(const char *); i++) {
  334. FcPattern *pattern = FcPatternCreate();
  335. ERR_CONTINUE(!pattern);
  336. FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
  337. FcPatternAddString(pattern, FC_FONTFORMAT, reinterpret_cast<const FcChar8 *>(allowed_formats[i]));
  338. FcFontSet *font_set = FcFontList(config, pattern, object_set);
  339. if (font_set) {
  340. for (int j = 0; j < font_set->nfont; j++) {
  341. char *family_name = nullptr;
  342. if (FcPatternGetString(font_set->fonts[j], FC_FAMILY, 0, reinterpret_cast<FcChar8 **>(&family_name)) == FcResultMatch) {
  343. if (family_name) {
  344. font_names.insert(String::utf8(family_name));
  345. }
  346. }
  347. }
  348. FcFontSetDestroy(font_set);
  349. }
  350. FcPatternDestroy(pattern);
  351. }
  352. FcObjectSetDestroy(object_set);
  353. FcConfigDestroy(config);
  354. for (const String &E : font_names) {
  355. ret.push_back(E);
  356. }
  357. return ret;
  358. #else
  359. ERR_FAIL_V_MSG(Vector<String>(), "Godot was compiled without fontconfig, system font support is disabled.");
  360. #endif
  361. }
  362. String OS_LinuxBSD::get_system_font_path(const String &p_font_name, bool p_bold, bool p_italic) const {
  363. #ifdef FONTCONFIG_ENABLED
  364. if (!font_config_initialized) {
  365. ERR_FAIL_V_MSG(String(), "Unable to load fontconfig, system font support is disabled.");
  366. }
  367. String ret;
  368. FcConfig *config = FcInitLoadConfigAndFonts();
  369. ERR_FAIL_COND_V(!config, ret);
  370. FcObjectSet *object_set = FcObjectSetBuild(FC_FAMILY, FC_FILE, nullptr);
  371. ERR_FAIL_COND_V(!object_set, ret);
  372. FcPattern *pattern = FcPatternCreate();
  373. if (pattern) {
  374. FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
  375. FcPatternAddString(pattern, FC_FAMILY, reinterpret_cast<const FcChar8 *>(p_font_name.utf8().get_data()));
  376. FcPatternAddInteger(pattern, FC_WEIGHT, p_bold ? FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL);
  377. FcPatternAddInteger(pattern, FC_SLANT, p_italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN);
  378. FcConfigSubstitute(0, pattern, FcMatchPattern);
  379. FcDefaultSubstitute(pattern);
  380. FcResult result;
  381. FcPattern *match = FcFontMatch(0, pattern, &result);
  382. if (match) {
  383. char *file_name = nullptr;
  384. if (FcPatternGetString(match, FC_FILE, 0, reinterpret_cast<FcChar8 **>(&file_name)) == FcResultMatch) {
  385. if (file_name) {
  386. ret = String::utf8(file_name);
  387. }
  388. }
  389. FcPatternDestroy(match);
  390. }
  391. FcPatternDestroy(pattern);
  392. }
  393. FcObjectSetDestroy(object_set);
  394. FcConfigDestroy(config);
  395. return ret;
  396. #else
  397. ERR_FAIL_V_MSG(String(), "Godot was compiled without fontconfig, system font support is disabled.");
  398. #endif
  399. }
  400. String OS_LinuxBSD::get_config_path() const {
  401. if (has_environment("XDG_CONFIG_HOME")) {
  402. if (get_environment("XDG_CONFIG_HOME").is_absolute_path()) {
  403. return get_environment("XDG_CONFIG_HOME");
  404. } else {
  405. 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.");
  406. return has_environment("HOME") ? get_environment("HOME").path_join(".config") : ".";
  407. }
  408. } else if (has_environment("HOME")) {
  409. return get_environment("HOME").path_join(".config");
  410. } else {
  411. return ".";
  412. }
  413. }
  414. String OS_LinuxBSD::get_data_path() const {
  415. if (has_environment("XDG_DATA_HOME")) {
  416. if (get_environment("XDG_DATA_HOME").is_absolute_path()) {
  417. return get_environment("XDG_DATA_HOME");
  418. } else {
  419. 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.");
  420. return has_environment("HOME") ? get_environment("HOME").path_join(".local/share") : get_config_path();
  421. }
  422. } else if (has_environment("HOME")) {
  423. return get_environment("HOME").path_join(".local/share");
  424. } else {
  425. return get_config_path();
  426. }
  427. }
  428. String OS_LinuxBSD::get_cache_path() const {
  429. if (has_environment("XDG_CACHE_HOME")) {
  430. if (get_environment("XDG_CACHE_HOME").is_absolute_path()) {
  431. return get_environment("XDG_CACHE_HOME");
  432. } else {
  433. 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.");
  434. return has_environment("HOME") ? get_environment("HOME").path_join(".cache") : get_config_path();
  435. }
  436. } else if (has_environment("HOME")) {
  437. return get_environment("HOME").path_join(".cache");
  438. } else {
  439. return get_config_path();
  440. }
  441. }
  442. String OS_LinuxBSD::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  443. String xdgparam;
  444. switch (p_dir) {
  445. case SYSTEM_DIR_DESKTOP: {
  446. xdgparam = "DESKTOP";
  447. } break;
  448. case SYSTEM_DIR_DCIM: {
  449. xdgparam = "PICTURES";
  450. } break;
  451. case SYSTEM_DIR_DOCUMENTS: {
  452. xdgparam = "DOCUMENTS";
  453. } break;
  454. case SYSTEM_DIR_DOWNLOADS: {
  455. xdgparam = "DOWNLOAD";
  456. } break;
  457. case SYSTEM_DIR_MOVIES: {
  458. xdgparam = "VIDEOS";
  459. } break;
  460. case SYSTEM_DIR_MUSIC: {
  461. xdgparam = "MUSIC";
  462. } break;
  463. case SYSTEM_DIR_PICTURES: {
  464. xdgparam = "PICTURES";
  465. } break;
  466. case SYSTEM_DIR_RINGTONES: {
  467. xdgparam = "MUSIC";
  468. } break;
  469. }
  470. String pipe;
  471. List<String> arg;
  472. arg.push_back(xdgparam);
  473. Error err = const_cast<OS_LinuxBSD *>(this)->execute("xdg-user-dir", arg, &pipe);
  474. if (err != OK) {
  475. return ".";
  476. }
  477. return pipe.strip_edges();
  478. }
  479. void OS_LinuxBSD::run() {
  480. if (!main_loop) {
  481. return;
  482. }
  483. main_loop->initialize();
  484. //uint64_t last_ticks=get_ticks_usec();
  485. //int frames=0;
  486. //uint64_t frame=0;
  487. while (true) {
  488. DisplayServer::get_singleton()->process_events(); // get rid of pending events
  489. #ifdef JOYDEV_ENABLED
  490. joypad->process_joypads();
  491. #endif
  492. if (Main::iteration()) {
  493. break;
  494. }
  495. }
  496. main_loop->finalize();
  497. }
  498. void OS_LinuxBSD::disable_crash_handler() {
  499. crash_handler.disable();
  500. }
  501. bool OS_LinuxBSD::is_disable_crash_handler() const {
  502. return crash_handler.is_disabled();
  503. }
  504. static String get_mountpoint(const String &p_path) {
  505. struct stat s;
  506. if (stat(p_path.utf8().get_data(), &s)) {
  507. return "";
  508. }
  509. #ifdef HAVE_MNTENT
  510. dev_t dev = s.st_dev;
  511. FILE *fd = setmntent("/proc/mounts", "r");
  512. if (!fd) {
  513. return "";
  514. }
  515. struct mntent mnt;
  516. char buf[1024];
  517. size_t buflen = 1024;
  518. while (getmntent_r(fd, &mnt, buf, buflen)) {
  519. if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) {
  520. endmntent(fd);
  521. return String(mnt.mnt_dir);
  522. }
  523. }
  524. endmntent(fd);
  525. #endif
  526. return "";
  527. }
  528. Error OS_LinuxBSD::move_to_trash(const String &p_path) {
  529. String path = p_path.rstrip("/"); // Strip trailing slash when path points to a directory
  530. int err_code;
  531. List<String> args;
  532. args.push_back(path);
  533. args.push_front("trash"); // The command is `gio trash <file_name>` so we need to add it to args.
  534. Error result = execute("gio", args, nullptr, &err_code); // For GNOME based machines.
  535. if (result == OK && !err_code) {
  536. return OK;
  537. } else if (err_code == 2) {
  538. return ERR_FILE_NOT_FOUND;
  539. }
  540. args.pop_front();
  541. args.push_front("move");
  542. args.push_back("trash:/"); // The command is `kioclient5 move <file_name> trash:/`.
  543. result = execute("kioclient5", args, nullptr, &err_code); // For KDE based machines.
  544. if (result == OK && !err_code) {
  545. return OK;
  546. } else if (err_code == 2) {
  547. return ERR_FILE_NOT_FOUND;
  548. }
  549. args.pop_front();
  550. args.pop_back();
  551. result = execute("gvfs-trash", args, nullptr, &err_code); // For older Linux machines.
  552. if (result == OK && !err_code) {
  553. return OK;
  554. } else if (err_code == 2) {
  555. return ERR_FILE_NOT_FOUND;
  556. }
  557. // If the commands `kioclient5`, `gio` or `gvfs-trash` don't exist on the system we do it manually.
  558. String trash_path = "";
  559. String mnt = get_mountpoint(path);
  560. // If there is a directory "[Mountpoint]/.Trash-[UID], use it as the trash can.
  561. if (!mnt.is_empty()) {
  562. String mountpoint_trash_path(mnt + "/.Trash-" + itos(getuid()));
  563. struct stat s;
  564. if (!stat(mountpoint_trash_path.utf8().get_data(), &s)) {
  565. trash_path = mountpoint_trash_path;
  566. }
  567. }
  568. // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash" as the trash can.
  569. if (trash_path.is_empty()) {
  570. char *dhome = getenv("XDG_DATA_HOME");
  571. if (dhome) {
  572. trash_path = String::utf8(dhome) + "/Trash";
  573. }
  574. }
  575. // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash" as the trash can.
  576. if (trash_path.is_empty()) {
  577. char *home = getenv("HOME");
  578. if (home) {
  579. trash_path = String::utf8(home) + "/.local/share/Trash";
  580. }
  581. }
  582. // Issue an error if none of the previous locations is appropriate for the trash can.
  583. ERR_FAIL_COND_V_MSG(trash_path.is_empty(), FAILED, "Could not determine the trash can location");
  584. // Create needed directories for decided trash can location.
  585. {
  586. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  587. Error err = dir_access->make_dir_recursive(trash_path);
  588. // Issue an error if trash can is not created properly.
  589. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"");
  590. err = dir_access->make_dir_recursive(trash_path + "/files");
  591. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/files\"");
  592. err = dir_access->make_dir_recursive(trash_path + "/info");
  593. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/info\"");
  594. }
  595. // The trash can is successfully created, now we check that we don't exceed our file name length limit.
  596. // If the file name is too long trim it so we can add the identifying number and ".trashinfo".
  597. // Assumes that the file name length limit is 255 characters.
  598. String file_name = path.get_file();
  599. if (file_name.length() > 240) {
  600. file_name = file_name.substr(0, file_name.length() - 15);
  601. }
  602. String dest_path = trash_path + "/files/" + file_name;
  603. struct stat buff;
  604. int id_number = 0;
  605. String fn = file_name;
  606. // Checks if a resource with the same name already exist in the trash can,
  607. // if there is, add an identifying number to our resource's name.
  608. while (stat(dest_path.utf8().get_data(), &buff) == 0) {
  609. id_number++;
  610. // Added a limit to check for identically named files already on the trash can
  611. // if there are too many it could make the editor unresponsive.
  612. ERR_FAIL_COND_V_MSG(id_number > 99, FAILED, "Too many identically named resources already in the trash can.");
  613. fn = file_name + "." + itos(id_number);
  614. dest_path = trash_path + "/files/" + fn;
  615. }
  616. file_name = fn;
  617. String renamed_path = path.get_base_dir() + "/" + file_name;
  618. // Generates the .trashinfo file
  619. OS::DateTime dt = OS::get_singleton()->get_datetime(false);
  620. String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", dt.year, (int)dt.month, dt.day, dt.hour, dt.minute);
  621. timestamp = vformat("%s%02d", timestamp, dt.second); // vformat only supports up to 6 arguments.
  622. String trash_info = "[Trash Info]\nPath=" + path.uri_encode() + "\nDeletionDate=" + timestamp + "\n";
  623. {
  624. Error err;
  625. {
  626. Ref<FileAccess> file = FileAccess::open(trash_path + "/info/" + file_name + ".trashinfo", FileAccess::WRITE, &err);
  627. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't create trashinfo file: \"" + trash_path + "/info/" + file_name + ".trashinfo\"");
  628. file->store_string(trash_info);
  629. }
  630. // Rename our resource before moving it to the trash can.
  631. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  632. err = dir_access->rename(path, renamed_path);
  633. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't rename file \"" + path + "\" to \"" + renamed_path + "\"");
  634. }
  635. // Move the given resource to the trash can.
  636. // Do not use DirAccess:rename() because it can't move files across multiple mountpoints.
  637. List<String> mv_args;
  638. mv_args.push_back(renamed_path);
  639. mv_args.push_back(trash_path + "/files");
  640. {
  641. int retval;
  642. Error err = execute("mv", mv_args, nullptr, &retval);
  643. // Issue an error if "mv" failed to move the given resource to the trash can.
  644. if (err != OK || retval != 0) {
  645. ERR_PRINT("move_to_trash: Could not move the resource \"" + path + "\" to the trash can \"" + trash_path + "/files\"");
  646. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  647. err = dir_access->rename(renamed_path, path);
  648. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not rename \"" + renamed_path + "\" back to its original name: \"" + path + "\"");
  649. return FAILED;
  650. }
  651. }
  652. return OK;
  653. }
  654. OS_LinuxBSD::OS_LinuxBSD() {
  655. main_loop = nullptr;
  656. #ifdef PULSEAUDIO_ENABLED
  657. AudioDriverManager::add_driver(&driver_pulseaudio);
  658. #endif
  659. #ifdef ALSA_ENABLED
  660. AudioDriverManager::add_driver(&driver_alsa);
  661. #endif
  662. #ifdef X11_ENABLED
  663. DisplayServerX11::register_x11_driver();
  664. #endif
  665. #ifdef FONTCONFIG_ENABLED
  666. #ifdef DEBUG_ENABLED
  667. int dylibloader_verbose = 1;
  668. #else
  669. int dylibloader_verbose = 0;
  670. #endif
  671. font_config_initialized = (initialize_fontconfig(dylibloader_verbose) == 0);
  672. #endif // FONTCONFIG_ENABLED
  673. }