os_linuxbsd.cpp 23 KB

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