os_linuxbsd.cpp 16 KB

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