os_linuxbsd.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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/fontconfig.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. HashSet<String> font_names;
  291. Vector<String> ret;
  292. FcConfig *config = FcInitLoadConfigAndFonts();
  293. ERR_FAIL_COND_V(!config, ret);
  294. FcObjectSet *object_set = FcObjectSetBuild(FC_FAMILY, nullptr);
  295. ERR_FAIL_COND_V(!object_set, ret);
  296. static const char *allowed_formats[] = { "TrueType", "CFF" };
  297. for (size_t i = 0; i < sizeof(allowed_formats) / sizeof(const char *); i++) {
  298. FcPattern *pattern = FcPatternCreate();
  299. ERR_CONTINUE(!pattern);
  300. FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
  301. FcPatternAddString(pattern, FC_FONTFORMAT, reinterpret_cast<const FcChar8 *>(allowed_formats[i]));
  302. FcFontSet *font_set = FcFontList(config, pattern, object_set);
  303. if (font_set) {
  304. for (int j = 0; j < font_set->nfont; j++) {
  305. char *family_name = nullptr;
  306. if (FcPatternGetString(font_set->fonts[j], FC_FAMILY, 0, reinterpret_cast<FcChar8 **>(&family_name)) == FcResultMatch) {
  307. if (family_name) {
  308. font_names.insert(String::utf8(family_name));
  309. }
  310. }
  311. }
  312. FcFontSetDestroy(font_set);
  313. }
  314. FcPatternDestroy(pattern);
  315. }
  316. FcObjectSetDestroy(object_set);
  317. for (const String &E : font_names) {
  318. ret.push_back(E);
  319. }
  320. return ret;
  321. #else
  322. ERR_FAIL_COND_V_MSG(Vector<String>(), "Godot was compiled without fontconfig, system font support is disabled.")
  323. #endif
  324. }
  325. String OS_LinuxBSD::get_system_font_path(const String &p_font_name, bool p_bold, bool p_italic) const {
  326. #ifdef FONTCONFIG_ENABLED
  327. String ret;
  328. FcConfig *config = FcInitLoadConfigAndFonts();
  329. ERR_FAIL_COND_V(!config, ret);
  330. FcObjectSet *object_set = FcObjectSetBuild(FC_FAMILY, FC_FILE, nullptr);
  331. ERR_FAIL_COND_V(!object_set, ret);
  332. FcPattern *pattern = FcPatternCreate();
  333. if (pattern) {
  334. FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
  335. FcPatternAddString(pattern, FC_FAMILY, reinterpret_cast<const FcChar8 *>(p_font_name.utf8().get_data()));
  336. FcPatternAddInteger(pattern, FC_WEIGHT, p_bold ? FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL);
  337. FcPatternAddInteger(pattern, FC_SLANT, p_italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN);
  338. FcConfigSubstitute(0, pattern, FcMatchPattern);
  339. FcDefaultSubstitute(pattern);
  340. FcResult result;
  341. FcPattern *match = FcFontMatch(0, pattern, &result);
  342. if (match) {
  343. char *file_name = nullptr;
  344. if (FcPatternGetString(match, FC_FILE, 0, reinterpret_cast<FcChar8 **>(&file_name)) == FcResultMatch) {
  345. if (file_name) {
  346. ret = String::utf8(file_name);
  347. }
  348. }
  349. FcPatternDestroy(match);
  350. }
  351. FcPatternDestroy(pattern);
  352. }
  353. FcObjectSetDestroy(object_set);
  354. #else
  355. ERR_FAIL_COND_V_MSG(Vector<String>(), "Godot was compiled without fontconfig, system font support is disabled.")
  356. #endif
  357. return ret;
  358. }
  359. String OS_LinuxBSD::get_config_path() const {
  360. if (has_environment("XDG_CONFIG_HOME")) {
  361. if (get_environment("XDG_CONFIG_HOME").is_absolute_path()) {
  362. return get_environment("XDG_CONFIG_HOME");
  363. } else {
  364. 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.");
  365. return has_environment("HOME") ? get_environment("HOME").plus_file(".config") : ".";
  366. }
  367. } else if (has_environment("HOME")) {
  368. return get_environment("HOME").plus_file(".config");
  369. } else {
  370. return ".";
  371. }
  372. }
  373. String OS_LinuxBSD::get_data_path() const {
  374. if (has_environment("XDG_DATA_HOME")) {
  375. if (get_environment("XDG_DATA_HOME").is_absolute_path()) {
  376. return get_environment("XDG_DATA_HOME");
  377. } else {
  378. 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.");
  379. return has_environment("HOME") ? get_environment("HOME").plus_file(".local/share") : get_config_path();
  380. }
  381. } else if (has_environment("HOME")) {
  382. return get_environment("HOME").plus_file(".local/share");
  383. } else {
  384. return get_config_path();
  385. }
  386. }
  387. String OS_LinuxBSD::get_cache_path() const {
  388. if (has_environment("XDG_CACHE_HOME")) {
  389. if (get_environment("XDG_CACHE_HOME").is_absolute_path()) {
  390. return get_environment("XDG_CACHE_HOME");
  391. } else {
  392. 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.");
  393. return has_environment("HOME") ? get_environment("HOME").plus_file(".cache") : get_config_path();
  394. }
  395. } else if (has_environment("HOME")) {
  396. return get_environment("HOME").plus_file(".cache");
  397. } else {
  398. return get_config_path();
  399. }
  400. }
  401. String OS_LinuxBSD::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  402. String xdgparam;
  403. switch (p_dir) {
  404. case SYSTEM_DIR_DESKTOP: {
  405. xdgparam = "DESKTOP";
  406. } break;
  407. case SYSTEM_DIR_DCIM: {
  408. xdgparam = "PICTURES";
  409. } break;
  410. case SYSTEM_DIR_DOCUMENTS: {
  411. xdgparam = "DOCUMENTS";
  412. } break;
  413. case SYSTEM_DIR_DOWNLOADS: {
  414. xdgparam = "DOWNLOAD";
  415. } break;
  416. case SYSTEM_DIR_MOVIES: {
  417. xdgparam = "VIDEOS";
  418. } break;
  419. case SYSTEM_DIR_MUSIC: {
  420. xdgparam = "MUSIC";
  421. } break;
  422. case SYSTEM_DIR_PICTURES: {
  423. xdgparam = "PICTURES";
  424. } break;
  425. case SYSTEM_DIR_RINGTONES: {
  426. xdgparam = "MUSIC";
  427. } break;
  428. }
  429. String pipe;
  430. List<String> arg;
  431. arg.push_back(xdgparam);
  432. Error err = const_cast<OS_LinuxBSD *>(this)->execute("xdg-user-dir", arg, &pipe);
  433. if (err != OK) {
  434. return ".";
  435. }
  436. return pipe.strip_edges();
  437. }
  438. void OS_LinuxBSD::run() {
  439. force_quit = false;
  440. if (!main_loop) {
  441. return;
  442. }
  443. main_loop->initialize();
  444. //uint64_t last_ticks=get_ticks_usec();
  445. //int frames=0;
  446. //uint64_t frame=0;
  447. while (!force_quit) {
  448. DisplayServer::get_singleton()->process_events(); // get rid of pending events
  449. #ifdef JOYDEV_ENABLED
  450. joypad->process_joypads();
  451. #endif
  452. if (Main::iteration()) {
  453. break;
  454. }
  455. }
  456. main_loop->finalize();
  457. }
  458. void OS_LinuxBSD::disable_crash_handler() {
  459. crash_handler.disable();
  460. }
  461. bool OS_LinuxBSD::is_disable_crash_handler() const {
  462. return crash_handler.is_disabled();
  463. }
  464. static String get_mountpoint(const String &p_path) {
  465. struct stat s;
  466. if (stat(p_path.utf8().get_data(), &s)) {
  467. return "";
  468. }
  469. #ifdef HAVE_MNTENT
  470. dev_t dev = s.st_dev;
  471. FILE *fd = setmntent("/proc/mounts", "r");
  472. if (!fd) {
  473. return "";
  474. }
  475. struct mntent mnt;
  476. char buf[1024];
  477. size_t buflen = 1024;
  478. while (getmntent_r(fd, &mnt, buf, buflen)) {
  479. if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) {
  480. endmntent(fd);
  481. return String(mnt.mnt_dir);
  482. }
  483. }
  484. endmntent(fd);
  485. #endif
  486. return "";
  487. }
  488. Error OS_LinuxBSD::move_to_trash(const String &p_path) {
  489. String path = p_path.rstrip("/"); // Strip trailing slash when path points to a directory
  490. int err_code;
  491. List<String> args;
  492. args.push_back(path);
  493. args.push_front("trash"); // The command is `gio trash <file_name>` so we need to add it to args.
  494. Error result = execute("gio", args, nullptr, &err_code); // For GNOME based machines.
  495. if (result == OK && !err_code) {
  496. return OK;
  497. } else if (err_code == 2) {
  498. return ERR_FILE_NOT_FOUND;
  499. }
  500. args.pop_front();
  501. args.push_front("move");
  502. args.push_back("trash:/"); // The command is `kioclient5 move <file_name> trash:/`.
  503. result = execute("kioclient5", args, nullptr, &err_code); // For KDE based machines.
  504. if (result == OK && !err_code) {
  505. return OK;
  506. } else if (err_code == 2) {
  507. return ERR_FILE_NOT_FOUND;
  508. }
  509. args.pop_front();
  510. args.pop_back();
  511. result = execute("gvfs-trash", args, nullptr, &err_code); // For older Linux machines.
  512. if (result == OK && !err_code) {
  513. return OK;
  514. } else if (err_code == 2) {
  515. return ERR_FILE_NOT_FOUND;
  516. }
  517. // If the commands `kioclient5`, `gio` or `gvfs-trash` don't exist on the system we do it manually.
  518. String trash_path = "";
  519. String mnt = get_mountpoint(path);
  520. // If there is a directory "[Mountpoint]/.Trash-[UID], use it as the trash can.
  521. if (!mnt.is_empty()) {
  522. String mountpoint_trash_path(mnt + "/.Trash-" + itos(getuid()));
  523. struct stat s;
  524. if (!stat(mountpoint_trash_path.utf8().get_data(), &s)) {
  525. trash_path = mountpoint_trash_path;
  526. }
  527. }
  528. // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash" as the trash can.
  529. if (trash_path.is_empty()) {
  530. char *dhome = getenv("XDG_DATA_HOME");
  531. if (dhome) {
  532. trash_path = String::utf8(dhome) + "/Trash";
  533. }
  534. }
  535. // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash" as the trash can.
  536. if (trash_path.is_empty()) {
  537. char *home = getenv("HOME");
  538. if (home) {
  539. trash_path = String::utf8(home) + "/.local/share/Trash";
  540. }
  541. }
  542. // Issue an error if none of the previous locations is appropriate for the trash can.
  543. ERR_FAIL_COND_V_MSG(trash_path.is_empty(), FAILED, "Could not determine the trash can location");
  544. // Create needed directories for decided trash can location.
  545. {
  546. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  547. Error err = dir_access->make_dir_recursive(trash_path);
  548. // Issue an error if trash can is not created properly.
  549. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"");
  550. err = dir_access->make_dir_recursive(trash_path + "/files");
  551. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/files\"");
  552. err = dir_access->make_dir_recursive(trash_path + "/info");
  553. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/info\"");
  554. }
  555. // The trash can is successfully created, now we check that we don't exceed our file name length limit.
  556. // If the file name is too long trim it so we can add the identifying number and ".trashinfo".
  557. // Assumes that the file name length limit is 255 characters.
  558. String file_name = path.get_file();
  559. if (file_name.length() > 240) {
  560. file_name = file_name.substr(0, file_name.length() - 15);
  561. }
  562. String dest_path = trash_path + "/files/" + file_name;
  563. struct stat buff;
  564. int id_number = 0;
  565. String fn = file_name;
  566. // Checks if a resource with the same name already exist in the trash can,
  567. // if there is, add an identifying number to our resource's name.
  568. while (stat(dest_path.utf8().get_data(), &buff) == 0) {
  569. id_number++;
  570. // Added a limit to check for identically named files already on the trash can
  571. // if there are too many it could make the editor unresponsive.
  572. ERR_FAIL_COND_V_MSG(id_number > 99, FAILED, "Too many identically named resources already in the trash can.");
  573. fn = file_name + "." + itos(id_number);
  574. dest_path = trash_path + "/files/" + fn;
  575. }
  576. file_name = fn;
  577. String renamed_path = path.get_base_dir() + "/" + file_name;
  578. // Generates the .trashinfo file
  579. OS::Date date = OS::get_singleton()->get_date(false);
  580. OS::Time time = OS::get_singleton()->get_time(false);
  581. String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", date.year, (int)date.month, date.day, time.hour, time.minute);
  582. timestamp = vformat("%s%02d", timestamp, time.second); // vformat only supports up to 6 arguments.
  583. String trash_info = "[Trash Info]\nPath=" + path.uri_encode() + "\nDeletionDate=" + timestamp + "\n";
  584. {
  585. Error err;
  586. {
  587. Ref<FileAccess> file = FileAccess::open(trash_path + "/info/" + file_name + ".trashinfo", FileAccess::WRITE, &err);
  588. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't create trashinfo file: \"" + trash_path + "/info/" + file_name + ".trashinfo\"");
  589. file->store_string(trash_info);
  590. }
  591. // Rename our resource before moving it to the trash can.
  592. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  593. err = dir_access->rename(path, renamed_path);
  594. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't rename file \"" + path + "\" to \"" + renamed_path + "\"");
  595. }
  596. // Move the given resource to the trash can.
  597. // Do not use DirAccess:rename() because it can't move files across multiple mountpoints.
  598. List<String> mv_args;
  599. mv_args.push_back(renamed_path);
  600. mv_args.push_back(trash_path + "/files");
  601. {
  602. int retval;
  603. Error err = execute("mv", mv_args, nullptr, &retval);
  604. // Issue an error if "mv" failed to move the given resource to the trash can.
  605. if (err != OK || retval != 0) {
  606. ERR_PRINT("move_to_trash: Could not move the resource \"" + path + "\" to the trash can \"" + trash_path + "/files\"");
  607. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  608. err = dir_access->rename(renamed_path, path);
  609. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not rename \"" + renamed_path + "\" back to its original name: \"" + path + "\"");
  610. return FAILED;
  611. }
  612. }
  613. return OK;
  614. }
  615. OS_LinuxBSD::OS_LinuxBSD() {
  616. main_loop = nullptr;
  617. force_quit = false;
  618. #ifdef PULSEAUDIO_ENABLED
  619. AudioDriverManager::add_driver(&driver_pulseaudio);
  620. #endif
  621. #ifdef ALSA_ENABLED
  622. AudioDriverManager::add_driver(&driver_alsa);
  623. #endif
  624. #ifdef X11_ENABLED
  625. DisplayServerX11::register_x11_driver();
  626. #endif
  627. }