os_linuxbsd.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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. void OS_LinuxBSD::alert(const String &p_alert, const String &p_title) {
  49. const char *message_programs[] = { "zenity", "kdialog", "Xdialog", "xmessage" };
  50. String path = get_environment("PATH");
  51. Vector<String> path_elems = path.split(":", false);
  52. String program;
  53. for (int i = 0; i < path_elems.size(); i++) {
  54. for (uint64_t k = 0; k < sizeof(message_programs) / sizeof(char *); k++) {
  55. String tested_path = path_elems[i].plus_file(message_programs[k]);
  56. if (FileAccess::exists(tested_path)) {
  57. program = tested_path;
  58. break;
  59. }
  60. }
  61. if (program.length()) {
  62. break;
  63. }
  64. }
  65. List<String> args;
  66. if (program.ends_with("zenity")) {
  67. args.push_back("--error");
  68. args.push_back("--width");
  69. args.push_back("500");
  70. args.push_back("--title");
  71. args.push_back(p_title);
  72. args.push_back("--text");
  73. args.push_back(p_alert);
  74. }
  75. if (program.ends_with("kdialog")) {
  76. args.push_back("--error");
  77. args.push_back(p_alert);
  78. args.push_back("--title");
  79. args.push_back(p_title);
  80. }
  81. if (program.ends_with("Xdialog")) {
  82. args.push_back("--title");
  83. args.push_back(p_title);
  84. args.push_back("--msgbox");
  85. args.push_back(p_alert);
  86. args.push_back("0");
  87. args.push_back("0");
  88. }
  89. if (program.ends_with("xmessage")) {
  90. args.push_back("-center");
  91. args.push_back("-title");
  92. args.push_back(p_title);
  93. args.push_back(p_alert);
  94. }
  95. if (program.length()) {
  96. execute(program, args);
  97. } else {
  98. print_line(p_alert);
  99. }
  100. }
  101. void OS_LinuxBSD::initialize() {
  102. crash_handler.initialize();
  103. OS_Unix::initialize_core();
  104. }
  105. void OS_LinuxBSD::initialize_joypads() {
  106. #ifdef JOYDEV_ENABLED
  107. joypad = memnew(JoypadLinux(Input::get_singleton()));
  108. #endif
  109. }
  110. String OS_LinuxBSD::get_unique_id() const {
  111. static String machine_id;
  112. if (machine_id.is_empty()) {
  113. if (FileAccess *f = FileAccess::open("/etc/machine-id", FileAccess::READ)) {
  114. while (machine_id.is_empty() && !f->eof_reached()) {
  115. machine_id = f->get_line().strip_edges();
  116. }
  117. f->close();
  118. memdelete(f);
  119. }
  120. }
  121. return machine_id;
  122. }
  123. String OS_LinuxBSD::get_processor_name() const {
  124. FileAccessRef f = FileAccess::open("/proc/cpuinfo", FileAccess::READ);
  125. ERR_FAIL_COND_V_MSG(!f, "", String("Couldn't open `/proc/cpuinfo` to get the CPU model name. Returning an empty string."));
  126. while (!f->eof_reached()) {
  127. const String line = f->get_line();
  128. if (line.find("model name") != -1) {
  129. return line.split(":")[1].strip_edges();
  130. }
  131. }
  132. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name from `/proc/cpuinfo`. Returning an empty string."));
  133. }
  134. void OS_LinuxBSD::finalize() {
  135. if (main_loop) {
  136. memdelete(main_loop);
  137. }
  138. main_loop = nullptr;
  139. #ifdef ALSAMIDI_ENABLED
  140. driver_alsamidi.close();
  141. #endif
  142. #ifdef JOYDEV_ENABLED
  143. if (joypad) {
  144. memdelete(joypad);
  145. }
  146. #endif
  147. }
  148. MainLoop *OS_LinuxBSD::get_main_loop() const {
  149. return main_loop;
  150. }
  151. void OS_LinuxBSD::delete_main_loop() {
  152. if (main_loop) {
  153. memdelete(main_loop);
  154. }
  155. main_loop = nullptr;
  156. }
  157. void OS_LinuxBSD::set_main_loop(MainLoop *p_main_loop) {
  158. main_loop = p_main_loop;
  159. }
  160. String OS_LinuxBSD::get_name() const {
  161. #ifdef __linux__
  162. return "Linux";
  163. #elif defined(__FreeBSD__)
  164. return "FreeBSD";
  165. #elif defined(__NetBSD__)
  166. return "NetBSD";
  167. #elif defined(__OpenBSD__)
  168. return "OpenBSD";
  169. #else
  170. return "BSD";
  171. #endif
  172. }
  173. Error OS_LinuxBSD::shell_open(String p_uri) {
  174. Error ok;
  175. int err_code;
  176. List<String> args;
  177. args.push_back(p_uri);
  178. // Agnostic
  179. ok = execute("xdg-open", args, nullptr, &err_code);
  180. if (ok == OK && !err_code) {
  181. return OK;
  182. } else if (err_code == 2) {
  183. return ERR_FILE_NOT_FOUND;
  184. }
  185. // GNOME
  186. args.push_front("open"); // The command is `gio open`, so we need to add it to args
  187. ok = execute("gio", args, nullptr, &err_code);
  188. if (ok == OK && !err_code) {
  189. return OK;
  190. } else if (err_code == 2) {
  191. return ERR_FILE_NOT_FOUND;
  192. }
  193. args.pop_front();
  194. ok = execute("gvfs-open", args, nullptr, &err_code);
  195. if (ok == OK && !err_code) {
  196. return OK;
  197. } else if (err_code == 2) {
  198. return ERR_FILE_NOT_FOUND;
  199. }
  200. // KDE
  201. ok = execute("kde-open5", args, nullptr, &err_code);
  202. if (ok == OK && !err_code) {
  203. return OK;
  204. }
  205. ok = execute("kde-open", args, nullptr, &err_code);
  206. return !err_code ? ok : FAILED;
  207. }
  208. bool OS_LinuxBSD::_check_internal_feature_support(const String &p_feature) {
  209. return p_feature == "pc";
  210. }
  211. String OS_LinuxBSD::get_config_path() const {
  212. if (has_environment("XDG_CONFIG_HOME")) {
  213. if (get_environment("XDG_CONFIG_HOME").is_absolute_path()) {
  214. return get_environment("XDG_CONFIG_HOME");
  215. } else {
  216. 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.");
  217. return has_environment("HOME") ? get_environment("HOME").plus_file(".config") : ".";
  218. }
  219. } else if (has_environment("HOME")) {
  220. return get_environment("HOME").plus_file(".config");
  221. } else {
  222. return ".";
  223. }
  224. }
  225. String OS_LinuxBSD::get_data_path() const {
  226. if (has_environment("XDG_DATA_HOME")) {
  227. if (get_environment("XDG_DATA_HOME").is_absolute_path()) {
  228. return get_environment("XDG_DATA_HOME");
  229. } else {
  230. 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.");
  231. return has_environment("HOME") ? get_environment("HOME").plus_file(".local/share") : get_config_path();
  232. }
  233. } else if (has_environment("HOME")) {
  234. return get_environment("HOME").plus_file(".local/share");
  235. } else {
  236. return get_config_path();
  237. }
  238. }
  239. String OS_LinuxBSD::get_cache_path() const {
  240. if (has_environment("XDG_CACHE_HOME")) {
  241. if (get_environment("XDG_CACHE_HOME").is_absolute_path()) {
  242. return get_environment("XDG_CACHE_HOME");
  243. } else {
  244. 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.");
  245. return has_environment("HOME") ? get_environment("HOME").plus_file(".cache") : get_config_path();
  246. }
  247. } else if (has_environment("HOME")) {
  248. return get_environment("HOME").plus_file(".cache");
  249. } else {
  250. return get_config_path();
  251. }
  252. }
  253. String OS_LinuxBSD::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  254. String xdgparam;
  255. switch (p_dir) {
  256. case SYSTEM_DIR_DESKTOP: {
  257. xdgparam = "DESKTOP";
  258. } break;
  259. case SYSTEM_DIR_DCIM: {
  260. xdgparam = "PICTURES";
  261. } break;
  262. case SYSTEM_DIR_DOCUMENTS: {
  263. xdgparam = "DOCUMENTS";
  264. } break;
  265. case SYSTEM_DIR_DOWNLOADS: {
  266. xdgparam = "DOWNLOAD";
  267. } break;
  268. case SYSTEM_DIR_MOVIES: {
  269. xdgparam = "VIDEOS";
  270. } break;
  271. case SYSTEM_DIR_MUSIC: {
  272. xdgparam = "MUSIC";
  273. } break;
  274. case SYSTEM_DIR_PICTURES: {
  275. xdgparam = "PICTURES";
  276. } break;
  277. case SYSTEM_DIR_RINGTONES: {
  278. xdgparam = "MUSIC";
  279. } break;
  280. }
  281. String pipe;
  282. List<String> arg;
  283. arg.push_back(xdgparam);
  284. Error err = const_cast<OS_LinuxBSD *>(this)->execute("xdg-user-dir", arg, &pipe);
  285. if (err != OK) {
  286. return ".";
  287. }
  288. return pipe.strip_edges();
  289. }
  290. void OS_LinuxBSD::run() {
  291. force_quit = false;
  292. if (!main_loop) {
  293. return;
  294. }
  295. main_loop->initialize();
  296. //uint64_t last_ticks=get_ticks_usec();
  297. //int frames=0;
  298. //uint64_t frame=0;
  299. while (!force_quit) {
  300. DisplayServer::get_singleton()->process_events(); // get rid of pending events
  301. #ifdef JOYDEV_ENABLED
  302. joypad->process_joypads();
  303. #endif
  304. if (Main::iteration()) {
  305. break;
  306. }
  307. }
  308. main_loop->finalize();
  309. }
  310. void OS_LinuxBSD::disable_crash_handler() {
  311. crash_handler.disable();
  312. }
  313. bool OS_LinuxBSD::is_disable_crash_handler() const {
  314. return crash_handler.is_disabled();
  315. }
  316. static String get_mountpoint(const String &p_path) {
  317. struct stat s;
  318. if (stat(p_path.utf8().get_data(), &s)) {
  319. return "";
  320. }
  321. #ifdef HAVE_MNTENT
  322. dev_t dev = s.st_dev;
  323. FILE *fd = setmntent("/proc/mounts", "r");
  324. if (!fd) {
  325. return "";
  326. }
  327. struct mntent mnt;
  328. char buf[1024];
  329. size_t buflen = 1024;
  330. while (getmntent_r(fd, &mnt, buf, buflen)) {
  331. if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) {
  332. endmntent(fd);
  333. return String(mnt.mnt_dir);
  334. }
  335. }
  336. endmntent(fd);
  337. #endif
  338. return "";
  339. }
  340. Error OS_LinuxBSD::move_to_trash(const String &p_path) {
  341. String path = p_path.rstrip("/"); // Strip trailing slash when path points to a directory
  342. int err_code;
  343. List<String> args;
  344. args.push_back(path);
  345. args.push_front("trash"); // The command is `gio trash <file_name>` so we need to add it to args.
  346. Error result = execute("gio", args, nullptr, &err_code); // For GNOME based machines.
  347. if (result == OK && !err_code) {
  348. return OK;
  349. } else if (err_code == 2) {
  350. return ERR_FILE_NOT_FOUND;
  351. }
  352. args.pop_front();
  353. args.push_front("move");
  354. args.push_back("trash:/"); // The command is `kioclient5 move <file_name> trash:/`.
  355. result = execute("kioclient5", args, nullptr, &err_code); // For KDE based machines.
  356. if (result == OK && !err_code) {
  357. return OK;
  358. } else if (err_code == 2) {
  359. return ERR_FILE_NOT_FOUND;
  360. }
  361. args.pop_front();
  362. args.pop_back();
  363. result = execute("gvfs-trash", args, nullptr, &err_code); // For older Linux machines.
  364. if (result == OK && !err_code) {
  365. return OK;
  366. } else if (err_code == 2) {
  367. return ERR_FILE_NOT_FOUND;
  368. }
  369. // If the commands `kioclient5`, `gio` or `gvfs-trash` don't exist on the system we do it manually.
  370. String trash_path = "";
  371. String mnt = get_mountpoint(path);
  372. // If there is a directory "[Mountpoint]/.Trash-[UID], use it as the trash can.
  373. if (!mnt.is_empty()) {
  374. String mountpoint_trash_path(mnt + "/.Trash-" + itos(getuid()));
  375. struct stat s;
  376. if (!stat(mountpoint_trash_path.utf8().get_data(), &s)) {
  377. trash_path = mountpoint_trash_path;
  378. }
  379. }
  380. // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash" as the trash can.
  381. if (trash_path.is_empty()) {
  382. char *dhome = getenv("XDG_DATA_HOME");
  383. if (dhome) {
  384. trash_path = String::utf8(dhome) + "/Trash";
  385. }
  386. }
  387. // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash" as the trash can.
  388. if (trash_path.is_empty()) {
  389. char *home = getenv("HOME");
  390. if (home) {
  391. trash_path = String::utf8(home) + "/.local/share/Trash";
  392. }
  393. }
  394. // Issue an error if none of the previous locations is appropriate for the trash can.
  395. ERR_FAIL_COND_V_MSG(trash_path.is_empty(), FAILED, "Could not determine the trash can location");
  396. // Create needed directories for decided trash can location.
  397. {
  398. DirAccessRef dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  399. Error err = dir_access->make_dir_recursive(trash_path);
  400. // Issue an error if trash can is not created properly.
  401. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"");
  402. err = dir_access->make_dir_recursive(trash_path + "/files");
  403. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/files\"");
  404. err = dir_access->make_dir_recursive(trash_path + "/info");
  405. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "/info\"");
  406. }
  407. // The trash can is successfully created, now we check that we don't exceed our file name length limit.
  408. // If the file name is too long trim it so we can add the identifying number and ".trashinfo".
  409. // Assumes that the file name length limit is 255 characters.
  410. String file_name = path.get_file();
  411. if (file_name.length() > 240) {
  412. file_name = file_name.substr(0, file_name.length() - 15);
  413. }
  414. String dest_path = trash_path + "/files/" + file_name;
  415. struct stat buff;
  416. int id_number = 0;
  417. String fn = file_name;
  418. // Checks if a resource with the same name already exist in the trash can,
  419. // if there is, add an identifying number to our resource's name.
  420. while (stat(dest_path.utf8().get_data(), &buff) == 0) {
  421. id_number++;
  422. // Added a limit to check for identically named files already on the trash can
  423. // if there are too many it could make the editor unresponsive.
  424. ERR_FAIL_COND_V_MSG(id_number > 99, FAILED, "Too many identically named resources already in the trash can.");
  425. fn = file_name + "." + itos(id_number);
  426. dest_path = trash_path + "/files/" + fn;
  427. }
  428. file_name = fn;
  429. String renamed_path = path.get_base_dir() + "/" + file_name;
  430. // Generates the .trashinfo file
  431. OS::Date date = OS::get_singleton()->get_date(false);
  432. OS::Time time = OS::get_singleton()->get_time(false);
  433. String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", date.year, (int)date.month, date.day, time.hour, time.minute);
  434. timestamp = vformat("%s%02d", timestamp, time.second); // vformat only supports up to 6 arguments.
  435. String trash_info = "[Trash Info]\nPath=" + path.uri_encode() + "\nDeletionDate=" + timestamp + "\n";
  436. {
  437. Error err;
  438. FileAccessRef file = FileAccess::open(trash_path + "/info/" + file_name + ".trashinfo", FileAccess::WRITE, &err);
  439. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't create trashinfo file: \"" + trash_path + "/info/" + file_name + ".trashinfo\"");
  440. file->store_string(trash_info);
  441. file->close();
  442. // Rename our resource before moving it to the trash can.
  443. DirAccessRef dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  444. err = dir_access->rename(path, renamed_path);
  445. ERR_FAIL_COND_V_MSG(err != OK, err, "Can't rename file \"" + path + "\" to \"" + renamed_path + "\"");
  446. }
  447. // Move the given resource to the trash can.
  448. // Do not use DirAccess:rename() because it can't move files across multiple mountpoints.
  449. List<String> mv_args;
  450. mv_args.push_back(renamed_path);
  451. mv_args.push_back(trash_path + "/files");
  452. {
  453. int retval;
  454. Error err = execute("mv", mv_args, nullptr, &retval);
  455. // Issue an error if "mv" failed to move the given resource to the trash can.
  456. if (err != OK || retval != 0) {
  457. ERR_PRINT("move_to_trash: Could not move the resource \"" + path + "\" to the trash can \"" + trash_path + "/files\"");
  458. DirAccessRef dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  459. err = dir_access->rename(renamed_path, path);
  460. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not rename \"" + renamed_path + "\" back to its original name: \"" + path + "\"");
  461. return FAILED;
  462. }
  463. }
  464. return OK;
  465. }
  466. OS_LinuxBSD::OS_LinuxBSD() {
  467. main_loop = nullptr;
  468. force_quit = false;
  469. #ifdef PULSEAUDIO_ENABLED
  470. AudioDriverManager::add_driver(&driver_pulseaudio);
  471. #endif
  472. #ifdef ALSA_ENABLED
  473. AudioDriverManager::add_driver(&driver_alsa);
  474. #endif
  475. #ifdef X11_ENABLED
  476. DisplayServerX11::register_x11_driver();
  477. #endif
  478. }