os_linuxbsd.cpp 22 KB

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