My build of nnn with minor changes
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

3033 行
63 KiB

  1. /* See LICENSE file for copyright and license details. */
  2. /*
  3. * Visual layout:
  4. * .---------
  5. * | DIR: /mnt/path
  6. * |
  7. * | file0
  8. * | file1
  9. * | > file2
  10. * | file3
  11. * | file4
  12. * ...
  13. * | filen
  14. * |
  15. * | Permission denied
  16. * '------
  17. */
  18. #ifdef __linux__
  19. #ifdef __i386__
  20. #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit Linux */
  21. #endif
  22. #include <sys/inotify.h>
  23. #define LINUX_INOTIFY
  24. #if !defined(__GLIBC__)
  25. #include <sys/types.h>
  26. #endif
  27. #endif
  28. #include <sys/resource.h>
  29. #include <sys/stat.h>
  30. #include <sys/statvfs.h>
  31. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  32. #include <sys/types.h>
  33. #include <sys/event.h>
  34. #include <sys/time.h>
  35. #define BSD_KQUEUE
  36. #else
  37. #include <sys/sysmacros.h>
  38. #endif
  39. #include <sys/wait.h>
  40. #include <ctype.h>
  41. #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
  42. #ifndef NCURSES_WIDECHAR
  43. #define NCURSES_WIDECHAR 1
  44. #endif
  45. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  46. #ifndef _XOPEN_SOURCE_EXTENDED
  47. #define _XOPEN_SOURCE_EXTENDED
  48. #endif
  49. #endif
  50. #ifndef __USE_XOPEN /* Fix failure due to wcswidth(), ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
  51. #define __USE_XOPEN
  52. #endif
  53. #include <curses.h>
  54. #include <dirent.h>
  55. #include <errno.h>
  56. #include <fcntl.h>
  57. #include <grp.h>
  58. #include <libgen.h>
  59. #include <limits.h>
  60. #ifdef __gnu_hurd__
  61. #define PATH_MAX 4096
  62. #endif
  63. #include <locale.h>
  64. #include <pwd.h>
  65. #include <regex.h>
  66. #include <signal.h>
  67. #include <stdarg.h>
  68. #include <stdio.h>
  69. #include <stdlib.h>
  70. #include <string.h>
  71. #include <time.h>
  72. #include <unistd.h>
  73. #include <readline/history.h>
  74. #include <readline/readline.h>
  75. #ifndef __USE_XOPEN_EXTENDED
  76. #define __USE_XOPEN_EXTENDED 1
  77. #endif
  78. #include <ftw.h>
  79. #include <wchar.h>
  80. #include "nnn.h"
  81. #ifdef DEBUGMODE
  82. static int DEBUG_FD;
  83. static int
  84. xprintf(int fd, const char *fmt, ...)
  85. {
  86. char buf[BUFSIZ];
  87. int r;
  88. va_list ap;
  89. va_start(ap, fmt);
  90. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  91. if (r > 0)
  92. r = write(fd, buf, r);
  93. va_end(ap);
  94. return r;
  95. }
  96. static int
  97. enabledbg()
  98. {
  99. FILE *fp = fopen("/tmp/nnn_debug", "w");
  100. if (!fp) {
  101. fprintf(stderr, "Cannot open debug file\n");
  102. return -1;
  103. }
  104. DEBUG_FD = fileno(fp);
  105. if (DEBUG_FD == -1) {
  106. fprintf(stderr, "Cannot open debug file descriptor\n");
  107. return -1;
  108. }
  109. return 0;
  110. }
  111. static void
  112. disabledbg()
  113. {
  114. close(DEBUG_FD);
  115. }
  116. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  117. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  118. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  119. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=%p\n", x)
  120. #else
  121. #define DPRINTF_D(x)
  122. #define DPRINTF_U(x)
  123. #define DPRINTF_S(x)
  124. #define DPRINTF_P(x)
  125. #endif /* DEBUGMODE */
  126. /* Macro definitions */
  127. #define VERSION "1.6"
  128. #define GENERAL_INFO "License: BSD 2-Clause\nWebpage: https://github.com/jarun/nnn"
  129. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  130. #undef MIN
  131. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  132. #define ISODD(x) ((x) & 1)
  133. #define TOUPPER(ch) \
  134. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  135. #define MAX_CMD_LEN 5120
  136. #define CWD "DIR: "
  137. #define CURSR " > "
  138. #define EMPTY " "
  139. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  140. #define FILTER '/'
  141. #define REGEX_MAX 128
  142. #define BM_MAX 10
  143. #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
  144. #define NAMEBUF_INCR 0x1000 /* 64 dir entries at a time, avg. 64 chars per filename = 64*64B = 4KB */
  145. #define DESCRIPTOR_LEN 32
  146. /* Macros to define process spawn behaviour as flags */
  147. #define F_NONE 0x00 /* no flag set */
  148. #define F_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
  149. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  150. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  151. #define F_SIGINT 0x08 /* restore default SIGINT handler */
  152. #define F_NORMAL 0x80 /* spawn child process in non-curses regular mode */
  153. #define exitcurses() endwin()
  154. #define clearprompt() printmsg("")
  155. #define printwarn() printmsg(strerror(errno))
  156. #define istopdir(path) (path[1] == '\0' && path[0] == '/')
  157. #define copyfilter() xstrlcpy(fltr, ifilter, NAME_MAX)
  158. #define copycurname() xstrlcpy(oldname, dents[cur].name, NAME_MAX + 1)
  159. #define settimeout() timeout(1000)
  160. #define cleartimeout() timeout(-1)
  161. #define errexit() printerr(__LINE__)
  162. #ifdef LINUX_INOTIFY
  163. #define EVENT_SIZE (sizeof(struct inotify_event))
  164. #define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
  165. #elif defined(BSD_KQUEUE)
  166. #define NUM_EVENT_SLOTS 1
  167. #define NUM_EVENT_FDS 1
  168. #endif
  169. /* TYPE DEFINITIONS */
  170. typedef unsigned long ulong;
  171. typedef unsigned int uint;
  172. typedef unsigned char uchar;
  173. /* STRUCTURES */
  174. /* Directory entry */
  175. typedef struct entry {
  176. char *name;
  177. time_t t;
  178. off_t size;
  179. blkcnt_t blocks; /* number of 512B blocks allocated */
  180. mode_t mode;
  181. uint nlen; /* Length of file name; can be uchar (< NAME_MAX + 1) */
  182. } *pEntry;
  183. /* Bookmark */
  184. typedef struct {
  185. char *key;
  186. char *loc;
  187. } bm;
  188. /* Settings */
  189. typedef struct {
  190. ushort filtermode : 1; /* Set to enter filter mode */
  191. ushort mtimeorder : 1; /* Set to sort by time modified */
  192. ushort sizeorder : 1; /* Set to sort by file size */
  193. ushort blkorder : 1; /* Set to sort by blocks used (disk usage) */
  194. ushort showhidden : 1; /* Set to show hidden files */
  195. ushort showdetail : 1; /* Clear to show fewer file info */
  196. ushort showcolor : 1; /* Set to show dirs in blue */
  197. ushort dircolor : 1; /* Current status of dir color */
  198. ushort metaviewer : 1; /* Index of metadata viewer in utils[] */
  199. ushort color : 3; /* Color code for directories */
  200. } settings;
  201. /* GLOBALS */
  202. /* Configuration */
  203. static settings cfg = {0, 0, 0, 0, 0, 1, 1, 0, 0, 4};
  204. static struct entry *dents;
  205. static char *pnamebuf;
  206. static int ndents, cur, total_dents;
  207. static uint idle;
  208. static uint idletimeout;
  209. static char *player;
  210. static char *copier;
  211. static char *editor;
  212. static char *desktop_manager;
  213. static char nowait = F_NOTRACE;
  214. static blkcnt_t ent_blocks;
  215. static blkcnt_t dir_blocks;
  216. static ulong num_files;
  217. static uint open_max;
  218. static bm bookmark[BM_MAX];
  219. #ifdef LINUX_INOTIFY
  220. static int inotify_fd, inotify_wd = -1;
  221. static uint INOTIFY_MASK = IN_ATTRIB | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  222. #elif defined(BSD_KQUEUE)
  223. static int kq, event_fd = -1;
  224. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  225. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  226. static struct timespec gtimeout;
  227. #endif
  228. /* Utilities to open files, run actions */
  229. static char * const utils[] = {
  230. "mediainfo",
  231. "exiftool",
  232. #ifdef __APPLE__
  233. "/usr/bin/open",
  234. #else
  235. "xdg-open",
  236. #endif
  237. "nlay",
  238. "atool"
  239. };
  240. /* Common message strings */
  241. static const char *STR_NFTWFAIL = "nftw(3) failed";
  242. static const char *STR_ATROOT = "You are at /";
  243. static const char *STR_NOHOME = "HOME not set";
  244. static const char *STR_INPUT = "No traversal delimiter allowed";
  245. static const char *STR_INVBM = "Invalid bookmark";
  246. /* For use in functions which are isolated and don't return the buffer */
  247. static char g_buf[MAX_CMD_LEN];
  248. /* Forward declarations */
  249. static void redraw(char *path);
  250. /* Functions */
  251. /* Messages show up at the bottom */
  252. static void
  253. printmsg(const char *msg)
  254. {
  255. mvprintw(LINES - 1, 0, "%s\n", msg);
  256. }
  257. /* Kill curses and display error before exiting */
  258. static void
  259. printerr(int linenum)
  260. {
  261. exitcurses();
  262. fprintf(stderr, "line %d: (%d) %s\n", linenum, errno, strerror(errno));
  263. exit(1);
  264. }
  265. /* Print prompt on the last line */
  266. static void
  267. printprompt(char *str)
  268. {
  269. clearprompt();
  270. printw(str);
  271. }
  272. /* Increase the limit on open file descriptors, if possible */
  273. static rlim_t
  274. max_openfds()
  275. {
  276. struct rlimit rl;
  277. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  278. if (limit != 0)
  279. return 32;
  280. limit = rl.rlim_cur;
  281. rl.rlim_cur = rl.rlim_max;
  282. /* Return ~75% of max possible */
  283. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  284. limit = rl.rlim_max - (rl.rlim_max >> 2);
  285. /*
  286. * 20K is arbitrary. If the limit is set to max possible
  287. * value, the memory usage increases to more than double.
  288. */
  289. return limit > 20480 ? 20480 : limit;
  290. }
  291. return limit;
  292. }
  293. /*
  294. * Custom xstrlen()
  295. */
  296. static size_t
  297. xstrlen(const char *s)
  298. {
  299. static size_t len;
  300. if (!s)
  301. return 0;
  302. len = 0;
  303. while (*s)
  304. ++len, ++s;
  305. return len;
  306. }
  307. /*
  308. * Just a safe strncpy(3)
  309. * Always null ('\0') terminates if both src and dest are valid pointers.
  310. * Returns the number of bytes copied including terminating null byte.
  311. */
  312. static size_t
  313. xstrlcpy(char *dest, const char *src, size_t n)
  314. {
  315. static size_t len, blocks;
  316. static const uint lsize = sizeof(ulong);
  317. static const uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
  318. if (!src || !dest)
  319. return 0;
  320. len = xstrlen(src) + 1;
  321. if (n > len)
  322. n = len;
  323. else if (len > n)
  324. /* Save total number of bytes to copy in len */
  325. len = n;
  326. if (n >= lsize) {
  327. blocks = n >> _WSHIFT;
  328. n -= (blocks << _WSHIFT);
  329. } else
  330. blocks = 0;
  331. if (blocks) {
  332. static ulong *s, *d;
  333. s = (ulong *)src;
  334. d = (ulong *)dest;
  335. while (blocks) {
  336. *d = *s;
  337. ++d, ++s;
  338. --blocks;
  339. }
  340. if (!n) {
  341. dest = (char *)d;
  342. *--dest = '\0';
  343. return len;
  344. }
  345. src = (char *)s;
  346. dest = (char *)d;
  347. }
  348. while (--n && (*dest = *src))
  349. ++dest, ++src;
  350. if (!n)
  351. *dest = '\0';
  352. return len;
  353. }
  354. /*
  355. * Custom strcmp(), just what we need.
  356. * Returns 0 if same, -ve if s1 < s2, +ve if s1 > s2.
  357. */
  358. static int
  359. xstrcmp(const char *s1, const char *s2)
  360. {
  361. if (!s1 || !s2)
  362. return -1;
  363. while (*s1 && *s1 == *s2)
  364. ++s1, ++s2;
  365. return *s1 - *s2;
  366. }
  367. /*
  368. * The poor man's implementation of memrchr(3).
  369. * We are only looking for '/' in this program.
  370. * And we are NOT expecting a '/' at the end.
  371. * Ideally 0 < n <= strlen(s).
  372. */
  373. static void *
  374. xmemrchr(uchar *s, uchar ch, size_t n)
  375. {
  376. static uchar *ptr;
  377. if (!s || !n)
  378. return NULL;
  379. ptr = s + n;
  380. do {
  381. --ptr;
  382. if (*ptr == ch)
  383. return ptr;
  384. } while (s != ptr);
  385. return NULL;
  386. }
  387. /*
  388. * The following dirname(3) implementation does not
  389. * modify the input. We use a copy of the original.
  390. *
  391. * Modified from the glibc (GNU LGPL) version.
  392. */
  393. static char *
  394. xdirname(const char *path)
  395. {
  396. static char * const buf = g_buf, *last_slash, *runp;
  397. xstrlcpy(buf, path, PATH_MAX);
  398. /* Find last '/'. */
  399. last_slash = xmemrchr((uchar *)buf, '/', xstrlen(buf));
  400. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  401. /* Determine whether all remaining characters are slashes. */
  402. for (runp = last_slash; runp != buf; --runp)
  403. if (runp[-1] != '/')
  404. break;
  405. /* The '/' is the last character, we have to look further. */
  406. if (runp != buf)
  407. last_slash = xmemrchr((uchar *)buf, '/', runp - buf);
  408. }
  409. if (last_slash != NULL) {
  410. /* Determine whether all remaining characters are slashes. */
  411. for (runp = last_slash; runp != buf; --runp)
  412. if (runp[-1] != '/')
  413. break;
  414. /* Terminate the buffer. */
  415. if (runp == buf) {
  416. /* The last slash is the first character in the string.
  417. * We have to return "/". As a special case we have to
  418. * return "//" if there are exactly two slashes at the
  419. * beginning of the string. See XBD 4.10 Path Name
  420. * Resolution for more information.
  421. */
  422. if (last_slash == buf + 1)
  423. ++last_slash;
  424. else
  425. last_slash = buf + 1;
  426. } else
  427. last_slash = runp;
  428. last_slash[0] = '\0';
  429. } else {
  430. /* This assignment is ill-designed but the XPG specs require to
  431. * return a string containing "." in any case no directory part
  432. * is found and so a static and constant string is required.
  433. */
  434. buf[0] = '.';
  435. buf[1] = '\0';
  436. }
  437. return buf;
  438. }
  439. static char *
  440. xbasename(char *path)
  441. {
  442. static char *base;
  443. base = xmemrchr((uchar *)path, '/', xstrlen(path));
  444. return base ? base + 1 : path;
  445. }
  446. /*
  447. * Return number of dots if all chars in a string are dots, else 0
  448. */
  449. static int
  450. all_dots(const char *path)
  451. {
  452. int count = 0;
  453. if (!path)
  454. return FALSE;
  455. while (*path == '.')
  456. ++count, ++path;
  457. if (*path)
  458. return 0;
  459. return count;
  460. }
  461. /* Initialize curses mode */
  462. static void
  463. initcurses(void)
  464. {
  465. if (initscr() == NULL) {
  466. char *term = getenv("TERM");
  467. if (term != NULL)
  468. fprintf(stderr, "error opening TERM: %s\n", term);
  469. else
  470. fprintf(stderr, "initscr() failed\n");
  471. exit(1);
  472. }
  473. cbreak();
  474. noecho();
  475. nonl();
  476. intrflush(stdscr, FALSE);
  477. keypad(stdscr, TRUE);
  478. curs_set(FALSE); /* Hide cursor */
  479. start_color();
  480. use_default_colors();
  481. if (cfg.showcolor)
  482. init_pair(1, cfg.color, -1);
  483. settimeout(); /* One second */
  484. }
  485. /*
  486. * Spawns a child process. Behaviour can be controlled using flag.
  487. * Limited to 2 arguments to a program, flag works on bit set.
  488. */
  489. static void
  490. spawn(const char *file, const char *arg1, const char *arg2, const char *dir, uchar flag)
  491. {
  492. static char *shlvl;
  493. static pid_t pid;
  494. static int status;
  495. if (flag & F_NORMAL)
  496. exitcurses();
  497. pid = fork();
  498. if (pid == 0) {
  499. if (dir != NULL)
  500. status = chdir(dir);
  501. shlvl = getenv("SHLVL");
  502. /* Show a marker (to indicate nnn spawned shell) */
  503. if (flag & F_MARKER && shlvl != NULL) {
  504. printf("\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  505. printf("Spawned shell level: %d\n", atoi(shlvl) + 1);
  506. }
  507. /* Suppress stdout and stderr */
  508. if (flag & F_NOTRACE) {
  509. int fd = open("/dev/null", O_WRONLY, 0200);
  510. dup2(fd, 1);
  511. dup2(fd, 2);
  512. close(fd);
  513. }
  514. if (flag & F_SIGINT)
  515. signal(SIGINT, SIG_DFL);
  516. execlp(file, file, arg1, arg2, NULL);
  517. _exit(1);
  518. } else {
  519. if (!(flag & F_NOWAIT))
  520. /* Ignore interruptions */
  521. while (waitpid(pid, &status, 0) == -1)
  522. DPRINTF_D(status);
  523. DPRINTF_D(pid);
  524. if (flag & F_NORMAL)
  525. initcurses();
  526. }
  527. }
  528. /* Get program name from env var, else return fallback program */
  529. static char *
  530. xgetenv(const char *name, char *fallback)
  531. {
  532. static char *value;
  533. if (name == NULL)
  534. return fallback;
  535. value = getenv(name);
  536. return value && value[0] ? value : fallback;
  537. }
  538. /* Check if a dir exists, IS a dir and is readable */
  539. static bool
  540. xdiraccess(const char *path)
  541. {
  542. static DIR *dirp;
  543. dirp = opendir(path);
  544. if (dirp == NULL) {
  545. printwarn();
  546. return FALSE;
  547. }
  548. closedir(dirp);
  549. return TRUE;
  550. }
  551. /*
  552. * We assume none of the strings are NULL.
  553. *
  554. * Let's have the logic to sort numeric names in numeric order.
  555. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  556. *
  557. * If the absolute numeric values are same, we fallback to alphasort.
  558. */
  559. static int
  560. xstricmp(const char * const s1, const char * const s2)
  561. {
  562. static const char *c1, *c2;
  563. c1 = s1;
  564. while (isspace(*c1))
  565. ++c1;
  566. c2 = s2;
  567. while (isspace(*c2))
  568. ++c2;
  569. if (*c1 == '-' || *c1 == '+')
  570. ++c1;
  571. if (*c2 == '-' || *c2 == '+')
  572. ++c2;
  573. if (isdigit(*c1) && isdigit(*c2)) {
  574. while (*c1 >= '0' && *c1 <= '9')
  575. ++c1;
  576. while (isspace(*c1))
  577. ++c1;
  578. while (*c2 >= '0' && *c2 <= '9')
  579. ++c2;
  580. while (isspace(*c2))
  581. ++c2;
  582. }
  583. if (!*c1 && !*c2) {
  584. static long long num1, num2;
  585. num1 = strtoll(s1, NULL, 10);
  586. num2 = strtoll(s2, NULL, 10);
  587. if (num1 != num2) {
  588. if (num1 > num2)
  589. return 1;
  590. else
  591. return -1;
  592. }
  593. }
  594. return strcoll(s1, s2);
  595. }
  596. /* Return the integer value of a char representing HEX */
  597. static char
  598. xchartohex(char c)
  599. {
  600. if (c >= '0' && c <= '9')
  601. return c - '0';
  602. c = TOUPPER(c);
  603. if (c >= 'A' && c <= 'F')
  604. return c - 'A' + 10;
  605. return c;
  606. }
  607. /* Trim all whitespace from both ends, / from end */
  608. static char *
  609. strstrip(char *s)
  610. {
  611. if (!s || !*s)
  612. return s;
  613. size_t len = xstrlen(s) - 1;
  614. while (len != 0 && (isspace(s[len]) || s[len] == '/'))
  615. --len;
  616. s[len + 1] = '\0';
  617. while (*s && isspace(*s))
  618. ++s;
  619. return s;
  620. }
  621. static char *
  622. getmime(const char *file)
  623. {
  624. static regex_t regex;
  625. static uint i;
  626. static const uint len = LEN(assocs);
  627. for (i = 0; i < len; ++i) {
  628. if (regcomp(&regex, assocs[i].regex, REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  629. continue;
  630. if (regexec(&regex, file, 0, NULL, 0) == 0)
  631. return assocs[i].mime;
  632. }
  633. return NULL;
  634. }
  635. static int
  636. setfilter(regex_t *regex, char *filter)
  637. {
  638. static size_t len;
  639. static int r;
  640. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  641. if (r != 0 && filter && filter[0] != '\0') {
  642. len = COLS;
  643. if (len > NAME_MAX)
  644. len = NAME_MAX;
  645. regerror(r, regex, g_buf, len);
  646. printmsg(g_buf);
  647. }
  648. return r;
  649. }
  650. static void
  651. initfilter(int dot, char **ifilter)
  652. {
  653. *ifilter = dot ? "." : "^[^.]";
  654. }
  655. static int
  656. visible(regex_t *regex, char *file)
  657. {
  658. return regexec(regex, file, 0, NULL, 0) == 0;
  659. }
  660. static int
  661. entrycmp(const void *va, const void *vb)
  662. {
  663. static pEntry pa, pb;
  664. pa = (pEntry)va;
  665. pb = (pEntry)vb;
  666. /* Sort directories first */
  667. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  668. return 1;
  669. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  670. return -1;
  671. /* Do the actual sorting */
  672. if (cfg.mtimeorder)
  673. return pb->t - pa->t;
  674. if (cfg.sizeorder) {
  675. if (pb->size > pa->size)
  676. return 1;
  677. else if (pb->size < pa->size)
  678. return -1;
  679. }
  680. if (cfg.blkorder) {
  681. if (pb->blocks > pa->blocks)
  682. return 1;
  683. else if (pb->blocks < pa->blocks)
  684. return -1;
  685. }
  686. return xstricmp(pa->name, pb->name);
  687. }
  688. /*
  689. * Returns SEL_* if key is bound and 0 otherwise.
  690. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  691. * The next keyboard input can be simulated by presel.
  692. */
  693. static int
  694. nextsel(char **run, char **env, int *presel)
  695. {
  696. static int c;
  697. static uint i;
  698. static const uint len = LEN(bindings);
  699. #ifdef LINUX_INOTIFY
  700. static char inotify_buf[EVENT_BUF_LEN];
  701. #elif defined(BSD_KQUEUE)
  702. static struct kevent event_data[NUM_EVENT_SLOTS];
  703. #endif
  704. c = *presel;
  705. if (c == 0)
  706. c = getch();
  707. else {
  708. *presel = 0;
  709. /* Unwatch dir if we are still in a filtered view */
  710. #ifdef LINUX_INOTIFY
  711. if (inotify_wd >= 0) {
  712. inotify_rm_watch(inotify_fd, inotify_wd);
  713. inotify_wd = -1;
  714. }
  715. #elif defined(BSD_KQUEUE)
  716. if (event_fd >= 0) {
  717. close(event_fd);
  718. event_fd = -1;
  719. }
  720. #endif
  721. }
  722. if (c == -1) {
  723. ++idle;
  724. /* Do not check for directory changes in du
  725. * mode. A redraw forces du calculation.
  726. * Check for changes every odd second.
  727. */
  728. #ifdef LINUX_INOTIFY
  729. if (!cfg.blkorder && inotify_wd >= 0 && idle & 1 && read(inotify_fd, inotify_buf, EVENT_BUF_LEN) > 0)
  730. #elif defined(BSD_KQUEUE)
  731. if (!cfg.blkorder && event_fd >= 0 && idle & 1
  732. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS, event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  733. #endif
  734. c = CONTROL('L');
  735. } else
  736. idle = 0;
  737. for (i = 0; i < len; ++i)
  738. if (c == bindings[i].sym) {
  739. *run = bindings[i].run;
  740. *env = bindings[i].env;
  741. return bindings[i].act;
  742. }
  743. return 0;
  744. }
  745. /*
  746. * Move non-matching entries to the end
  747. */
  748. static void
  749. fill(struct entry **dents, int (*filter)(regex_t *, char *), regex_t *re)
  750. {
  751. static int count;
  752. static struct entry _dent, *dentp1, *dentp2;
  753. for (count = 0; count < ndents; ++count) {
  754. if (filter(re, (*dents)[count].name) == 0) {
  755. if (count != --ndents) {
  756. dentp1 = &(*dents)[count];
  757. dentp2 = &(*dents)[ndents];
  758. memcpy(&_dent, dentp1, sizeof(struct entry));
  759. memcpy(dentp1, dentp2, sizeof(struct entry));
  760. memcpy(dentp2, &_dent, sizeof(struct entry));
  761. --count;
  762. }
  763. continue;
  764. }
  765. }
  766. }
  767. static int
  768. matches(char *fltr)
  769. {
  770. static regex_t re;
  771. /* Search filter */
  772. if (setfilter(&re, fltr) != 0)
  773. return -1;
  774. fill(&dents, visible, &re);
  775. qsort(dents, ndents, sizeof(*dents), entrycmp);
  776. return 0;
  777. }
  778. static int
  779. filterentries(char *path)
  780. {
  781. static char ln[REGEX_MAX];
  782. static wchar_t wln[REGEX_MAX];
  783. static wint_t ch[2] = {0};
  784. int r, total = ndents, oldcur = cur, len = 1;
  785. char *pln = ln + 1;
  786. ln[0] = wln[0] = FILTER;
  787. ln[1] = wln[1] = '\0';
  788. cur = 0;
  789. cleartimeout();
  790. echo();
  791. curs_set(TRUE);
  792. printprompt(ln);
  793. while ((r = get_wch(ch)) != ERR) {
  794. if (*ch == 127 /* handle DEL */ || *ch == KEY_DC || *ch == KEY_BACKSPACE) {
  795. if (len == 1) {
  796. cur = oldcur;
  797. *ch = CONTROL('L');
  798. goto end;
  799. }
  800. wln[--len] = '\0';
  801. if (len == 1)
  802. cur = oldcur;
  803. wcstombs(ln, wln, REGEX_MAX);
  804. ndents = total;
  805. if (matches(pln) == -1)
  806. continue;
  807. redraw(path);
  808. printprompt(ln);
  809. continue;
  810. }
  811. if (r == OK) {
  812. switch (*ch) {
  813. case '\r': // with nonl(), this is ENTER key value
  814. if (len == 1) {
  815. cur = oldcur;
  816. goto end;
  817. }
  818. if (matches(pln) == -1)
  819. goto end;
  820. redraw(path);
  821. goto end;
  822. case CONTROL('L'):
  823. if (len == 1)
  824. cur = oldcur; // fallthrough
  825. case CONTROL('Q'):
  826. goto end;
  827. default:
  828. /* Reset cur in case it's a repeat search */
  829. if (len == 1)
  830. cur = 0;
  831. if (len == REGEX_MAX - 1)
  832. break;
  833. wln[len] = (wchar_t)*ch;
  834. wln[++len] = '\0';
  835. wcstombs(ln, wln, REGEX_MAX);
  836. ndents = total;
  837. if (matches(pln) == -1)
  838. continue;
  839. redraw(path);
  840. printprompt(ln);
  841. }
  842. } else {
  843. if (len == 1)
  844. cur = oldcur;
  845. goto end;
  846. }
  847. }
  848. end:
  849. noecho();
  850. curs_set(FALSE);
  851. settimeout();
  852. /* Return keys for navigation etc. */
  853. return *ch;
  854. }
  855. /* Show a prompt with input string and return the changes */
  856. static char *
  857. xreadline(char *fname)
  858. {
  859. int old_curs = curs_set(1);
  860. size_t len, pos;
  861. int x, y, r;
  862. wint_t ch[2] = {0};
  863. wchar_t *buf = (wchar_t *)g_buf;
  864. size_t buflen = NAME_MAX - 1;
  865. if (fname) {
  866. DPRINTF_S(fname);
  867. len = pos = mbstowcs(buf, fname, NAME_MAX);
  868. } else
  869. len = (size_t)-1;
  870. if (len == (size_t)-1) {
  871. buf[0] = '\0';
  872. len = pos = 0;
  873. }
  874. getyx(stdscr, y, x);
  875. cleartimeout();
  876. while (1) {
  877. buf[len] = ' ';
  878. mvaddnwstr(y, x, buf, len + 1);
  879. move(y, x + wcswidth(buf, pos));
  880. if ((r = get_wch(ch)) != ERR) {
  881. if (r == OK) {
  882. if (*ch == KEY_ENTER || *ch == '\n' || *ch == '\r')
  883. break;
  884. if (*ch == CONTROL('L')) {
  885. clearprompt();
  886. len = pos = 0;
  887. continue;
  888. }
  889. /* TAB breaks cursor position, ignore it */
  890. if (*ch == '\t')
  891. continue;
  892. if (pos < buflen) {
  893. memmove(buf + pos + 1, buf + pos, (len - pos) << 2);
  894. buf[pos] = *ch;
  895. ++len, ++pos;
  896. continue;
  897. }
  898. } else {
  899. switch (*ch) {
  900. case KEY_LEFT:
  901. if (pos > 0)
  902. --pos;
  903. break;
  904. case KEY_RIGHT:
  905. if (pos < len)
  906. ++pos;
  907. break;
  908. case KEY_BACKSPACE:
  909. if (pos > 0) {
  910. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  911. --len, --pos;
  912. }
  913. break;
  914. case KEY_DC:
  915. if (pos < len) {
  916. memmove(buf + pos, buf + pos + 1, (len - pos - 1) << 2);
  917. --len;
  918. }
  919. break;
  920. default:
  921. break;
  922. }
  923. }
  924. }
  925. }
  926. buf[len] = '\0';
  927. if (old_curs != ERR)
  928. curs_set(old_curs);
  929. settimeout();
  930. DPRINTF_S(buf);
  931. wcstombs(g_buf, buf, NAME_MAX);
  932. return g_buf;
  933. }
  934. static char *
  935. readinput(void)
  936. {
  937. cleartimeout();
  938. echo();
  939. curs_set(TRUE);
  940. memset(g_buf, 0, NAME_MAX + 1);
  941. wgetnstr(stdscr, g_buf, NAME_MAX);
  942. noecho();
  943. curs_set(FALSE);
  944. settimeout();
  945. return g_buf[0] ? g_buf : NULL;
  946. }
  947. /*
  948. * Returns "dir/name or "/name"
  949. */
  950. static char *
  951. mkpath(char *dir, char *name, char *out, size_t n)
  952. {
  953. /* Handle absolute path */
  954. if (name[0] == '/')
  955. xstrlcpy(out, name, n);
  956. else {
  957. /* Handle root case */
  958. if (istopdir(dir))
  959. snprintf(out, n, "/%s", name);
  960. else
  961. snprintf(out, n, "%s/%s", dir, name);
  962. }
  963. return out;
  964. }
  965. static void
  966. parsebmstr(char *bms)
  967. {
  968. int i = 0;
  969. while (*bms && i < BM_MAX) {
  970. bookmark[i].key = bms;
  971. ++bms;
  972. while (*bms && *bms != ':')
  973. ++bms;
  974. if (!*bms) {
  975. bookmark[i].key = NULL;
  976. break;
  977. }
  978. *bms = '\0';
  979. bookmark[i].loc = ++bms;
  980. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  981. bookmark[i].key = NULL;
  982. break;
  983. }
  984. while (*bms && *bms != ';')
  985. ++bms;
  986. if (*bms)
  987. *bms = '\0';
  988. else
  989. break;
  990. ++bms;
  991. ++i;
  992. }
  993. }
  994. /*
  995. * Get the real path to a bookmark
  996. *
  997. * NULL is returned in case of no match, path resolution failure etc.
  998. * buf would be modified, so check return value before access
  999. */
  1000. static char *
  1001. get_bm_loc(char *key, char *buf)
  1002. {
  1003. int r;
  1004. if (!key || !key[0])
  1005. return NULL;
  1006. for (r = 0; bookmark[r].key && r < BM_MAX; ++r) {
  1007. if (xstrcmp(bookmark[r].key, key) == 0) {
  1008. if (bookmark[r].loc[0] == '~') {
  1009. char *home = getenv("HOME");
  1010. if (!home) {
  1011. DPRINTF_S(STR_NOHOME);
  1012. return NULL;
  1013. }
  1014. snprintf(buf, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  1015. } else
  1016. xstrlcpy(buf, bookmark[r].loc, PATH_MAX);
  1017. return buf;
  1018. }
  1019. }
  1020. DPRINTF_S("Invalid key");
  1021. return NULL;
  1022. }
  1023. static void
  1024. resetdircolor(mode_t mode)
  1025. {
  1026. if (cfg.dircolor && !S_ISDIR(mode)) {
  1027. attroff(COLOR_PAIR(1) | A_BOLD);
  1028. cfg.dircolor = 0;
  1029. }
  1030. }
  1031. /*
  1032. * Replace escape characters in a string with '?'
  1033. * Adjust string length to maxcols if > 0;
  1034. *
  1035. * Interestingly, note that buffer points to g_buf. What happens if
  1036. * str also points to g_buf? In this case we assume that the caller
  1037. * acknowledges that it's OK to lose the data in g_buf after this
  1038. * call to unescape().
  1039. * The API, on its part, first converts str to multibyte (after which
  1040. * it doesn't touch str anymore). Only after that it starts modifying
  1041. * buffer. This works like a phased operation.
  1042. */
  1043. static char *
  1044. unescape(const char *str, uint maxcols)
  1045. {
  1046. static wchar_t wbuf[PATH_MAX];
  1047. static char *buffer;
  1048. static wchar_t *buf;
  1049. static size_t len;
  1050. /* Convert multi-byte to wide char */
  1051. len = mbstowcs(wbuf, str, PATH_MAX);
  1052. buffer = g_buf;
  1053. buffer[0] = '\0';
  1054. buf = wbuf;
  1055. if (maxcols && len > maxcols) {
  1056. len = wcswidth(wbuf, len);
  1057. if (len > maxcols)
  1058. wbuf[maxcols] = 0;
  1059. }
  1060. while (*buf) {
  1061. if (*buf <= '\x1f' || *buf == '\x7f')
  1062. *buf = '\?';
  1063. ++buf;
  1064. }
  1065. /* Convert wide char to multi-byte */
  1066. wcstombs(buffer, wbuf, PATH_MAX);
  1067. return buffer;
  1068. }
  1069. static char *
  1070. coolsize(off_t size)
  1071. {
  1072. static const char * const U = "BKMGTPEZY";
  1073. static char size_buf[12]; /* Buffer to hold human readable size */
  1074. static int i;
  1075. static off_t tmp;
  1076. static long double rem;
  1077. static const double div_2_pow_10 = 1.0 / 1024.0;
  1078. i = 0;
  1079. rem = 0;
  1080. while (size > 1024) {
  1081. tmp = size;
  1082. size >>= 10;
  1083. rem = tmp - (size << 10);
  1084. ++i;
  1085. }
  1086. snprintf(size_buf, 12, "%.*Lf%c", i, size + rem * div_2_pow_10, U[i]);
  1087. return size_buf;
  1088. }
  1089. static void
  1090. printent(struct entry *ent, int sel, uint namecols)
  1091. {
  1092. static char *pname;
  1093. pname = unescape(ent->name, namecols);
  1094. /* Directories are always shown on top */
  1095. resetdircolor(ent->mode);
  1096. if (S_ISDIR(ent->mode))
  1097. printw("%s%s/\n", CURSYM(sel), pname);
  1098. else if (S_ISLNK(ent->mode))
  1099. printw("%s%s@\n", CURSYM(sel), pname);
  1100. else if (S_ISSOCK(ent->mode))
  1101. printw("%s%s=\n", CURSYM(sel), pname);
  1102. else if (S_ISFIFO(ent->mode))
  1103. printw("%s%s|\n", CURSYM(sel), pname);
  1104. else if (ent->mode & 0100)
  1105. printw("%s%s*\n", CURSYM(sel), pname);
  1106. else
  1107. printw("%s%s\n", CURSYM(sel), pname);
  1108. }
  1109. static void
  1110. printent_long(struct entry *ent, int sel, uint namecols)
  1111. {
  1112. static char buf[18], *pname;
  1113. strftime(buf, 18, "%d-%m-%Y %H:%M", localtime(&ent->t));
  1114. pname = unescape(ent->name, namecols);
  1115. /* Directories are always shown on top */
  1116. resetdircolor(ent->mode);
  1117. if (sel)
  1118. attron(A_REVERSE);
  1119. if (!cfg.blkorder) {
  1120. if (S_ISDIR(ent->mode))
  1121. printw("%s%-16.16s / %s/\n", CURSYM(sel), buf, pname);
  1122. else if (S_ISLNK(ent->mode))
  1123. printw("%s%-16.16s @ %s@\n", CURSYM(sel), buf, pname);
  1124. else if (S_ISSOCK(ent->mode))
  1125. printw("%s%-16.16s = %s=\n", CURSYM(sel), buf, pname);
  1126. else if (S_ISFIFO(ent->mode))
  1127. printw("%s%-16.16s | %s|\n", CURSYM(sel), buf, pname);
  1128. else if (S_ISBLK(ent->mode))
  1129. printw("%s%-16.16s b %s\n", CURSYM(sel), buf, pname);
  1130. else if (S_ISCHR(ent->mode))
  1131. printw("%s%-16.16s c %s\n", CURSYM(sel), buf, pname);
  1132. else if (ent->mode & 0100)
  1133. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1134. else
  1135. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1136. } else {
  1137. if (S_ISDIR(ent->mode))
  1138. printw("%s%-16.16s %8.8s/ %s/\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1139. else if (S_ISLNK(ent->mode))
  1140. printw("%s%-16.16s @ %s@\n", CURSYM(sel), buf, pname);
  1141. else if (S_ISSOCK(ent->mode))
  1142. printw("%s%-16.16s = %s=\n", CURSYM(sel), buf, pname);
  1143. else if (S_ISFIFO(ent->mode))
  1144. printw("%s%-16.16s | %s|\n", CURSYM(sel), buf, pname);
  1145. else if (S_ISBLK(ent->mode))
  1146. printw("%s%-16.16s b %s\n", CURSYM(sel), buf, pname);
  1147. else if (S_ISCHR(ent->mode))
  1148. printw("%s%-16.16s c %s\n", CURSYM(sel), buf, pname);
  1149. else if (ent->mode & 0100)
  1150. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1151. else
  1152. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1153. }
  1154. if (sel)
  1155. attroff(A_REVERSE);
  1156. }
  1157. static void (*printptr)(struct entry *ent, int sel, uint namecols) = &printent_long;
  1158. static char
  1159. get_fileind(mode_t mode, char *desc)
  1160. {
  1161. static char c;
  1162. if (S_ISREG(mode)) {
  1163. c = '-';
  1164. xstrlcpy(desc, "regular file", DESCRIPTOR_LEN);
  1165. if (mode & 0100)
  1166. xstrlcpy(desc + 12, ", executable", DESCRIPTOR_LEN - 12); /* Length of string "regular file" is 12 */
  1167. } else if (S_ISDIR(mode)) {
  1168. c = 'd';
  1169. xstrlcpy(desc, "directory", DESCRIPTOR_LEN);
  1170. } else if (S_ISBLK(mode)) {
  1171. c = 'b';
  1172. xstrlcpy(desc, "block special device", DESCRIPTOR_LEN);
  1173. } else if (S_ISCHR(mode)) {
  1174. c = 'c';
  1175. xstrlcpy(desc, "character special device", DESCRIPTOR_LEN);
  1176. #ifdef S_ISFIFO
  1177. } else if (S_ISFIFO(mode)) {
  1178. c = 'p';
  1179. xstrlcpy(desc, "FIFO", DESCRIPTOR_LEN);
  1180. #endif /* S_ISFIFO */
  1181. #ifdef S_ISLNK
  1182. } else if (S_ISLNK(mode)) {
  1183. c = 'l';
  1184. xstrlcpy(desc, "symbolic link", DESCRIPTOR_LEN);
  1185. #endif /* S_ISLNK */
  1186. #ifdef S_ISSOCK
  1187. } else if (S_ISSOCK(mode)) {
  1188. c = 's';
  1189. xstrlcpy(desc, "socket", DESCRIPTOR_LEN);
  1190. #endif /* S_ISSOCK */
  1191. #ifdef S_ISDOOR
  1192. /* Solaris 2.6, etc. */
  1193. } else if (S_ISDOOR(mode)) {
  1194. c = 'D';
  1195. desc[0] = '\0';
  1196. #endif /* S_ISDOOR */
  1197. } else {
  1198. /* Unknown type -- possibly a regular file? */
  1199. c = '?';
  1200. desc[0] = '\0';
  1201. }
  1202. return c;
  1203. }
  1204. /* Convert a mode field into "ls -l" type perms field. */
  1205. static char *
  1206. get_lsperms(mode_t mode, char *desc)
  1207. {
  1208. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1209. static char bits[11] = {'\0'};
  1210. bits[0] = get_fileind(mode, desc);
  1211. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  1212. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  1213. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  1214. if (mode & S_ISUID)
  1215. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1216. if (mode & S_ISGID)
  1217. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1218. if (mode & S_ISVTX)
  1219. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1220. return bits;
  1221. }
  1222. /*
  1223. * Gets only a single line (that's what we need
  1224. * for now) or shows full command output in pager.
  1225. *
  1226. * If pager is valid, returns NULL
  1227. */
  1228. static char *
  1229. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager)
  1230. {
  1231. pid_t pid;
  1232. int pipefd[2];
  1233. FILE *pf;
  1234. int tmp, flags;
  1235. char *ret = NULL;
  1236. if (pipe(pipefd) == -1)
  1237. errexit();
  1238. for (tmp = 0; tmp < 2; ++tmp) {
  1239. /* Get previous flags */
  1240. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1241. /* Set bit for non-blocking flag */
  1242. flags |= O_NONBLOCK;
  1243. /* Change flags on fd */
  1244. fcntl(pipefd[tmp], F_SETFL, flags);
  1245. }
  1246. pid = fork();
  1247. if (pid == 0) {
  1248. /* In child */
  1249. close(pipefd[0]);
  1250. dup2(pipefd[1], STDOUT_FILENO);
  1251. dup2(pipefd[1], STDERR_FILENO);
  1252. close(pipefd[1]);
  1253. execlp(file, file, arg1, arg2, NULL);
  1254. _exit(1);
  1255. }
  1256. /* In parent */
  1257. waitpid(pid, &tmp, 0);
  1258. close(pipefd[1]);
  1259. if (!pager) {
  1260. pf = fdopen(pipefd[0], "r");
  1261. if (pf) {
  1262. ret = fgets(buf, bytes, pf);
  1263. close(pipefd[0]);
  1264. }
  1265. return ret;
  1266. }
  1267. pid = fork();
  1268. if (pid == 0) {
  1269. /* Show in pager in child */
  1270. dup2(pipefd[0], STDIN_FILENO);
  1271. close(pipefd[0]);
  1272. execlp("less", "less", NULL);
  1273. _exit(1);
  1274. }
  1275. /* In parent */
  1276. waitpid(pid, &tmp, 0);
  1277. close(pipefd[0]);
  1278. return NULL;
  1279. }
  1280. /*
  1281. * Follows the stat(1) output closely
  1282. */
  1283. static int
  1284. show_stats(char *fpath, char *fname, struct stat *sb)
  1285. {
  1286. char desc[DESCRIPTOR_LEN];
  1287. char *perms = get_lsperms(sb->st_mode, desc);
  1288. char *p, *begin = g_buf;
  1289. char tmp[] = "/tmp/nnnXXXXXX";
  1290. int fd = mkstemp(tmp);
  1291. if (fd == -1)
  1292. return -1;
  1293. /* Show file name or 'symlink' -> 'target' */
  1294. if (perms[0] == 'l') {
  1295. /* Note that MAX_CMD_LEN > PATH_MAX */
  1296. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1297. if (len != -1) {
  1298. g_buf[len] = '\0';
  1299. dprintf(fd, " File: '%s' -> ", unescape(fname, 0));
  1300. /*
  1301. * We pass g_buf but unescape() operates on g_buf too!
  1302. * Read the API notes for information on how this works.
  1303. */
  1304. dprintf(fd, "'%s'", unescape(g_buf, 0));
  1305. }
  1306. } else
  1307. dprintf(fd, " File: '%s'", unescape(fname, 0));
  1308. /* Show size, blocks, file type */
  1309. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1310. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1311. (long long)sb->st_size, (long long)sb->st_blocks, sb->st_blksize, desc);
  1312. #else
  1313. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1314. sb->st_size, sb->st_blocks, (long)sb->st_blksize, desc);
  1315. #endif
  1316. /* Show containing device, inode, hardlink count */
  1317. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1318. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1319. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1320. g_buf, (unsigned long long)sb->st_ino, sb->st_nlink);
  1321. #else
  1322. sprintf(g_buf, "%lxh/%lud", (ulong)sb->st_dev, (ulong)sb->st_dev);
  1323. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1324. g_buf, sb->st_ino, (ulong)sb->st_nlink);
  1325. #endif
  1326. /* Show major, minor number for block or char device */
  1327. if (perms[0] == 'b' || perms[0] == 'c')
  1328. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1329. /* Show permissions, owner, group */
  1330. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)", (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7,
  1331. sb->st_mode & 7, perms, sb->st_uid, (getpwuid(sb->st_uid))->pw_name, sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1332. /* Show last access time */
  1333. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1334. dprintf(fd, "\n\n Access: %s", g_buf);
  1335. /* Show last modification time */
  1336. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1337. dprintf(fd, "\n Modify: %s", g_buf);
  1338. /* Show last status change time */
  1339. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1340. dprintf(fd, "\n Change: %s", g_buf);
  1341. if (S_ISREG(sb->st_mode)) {
  1342. /* Show file(1) output */
  1343. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1344. if (p) {
  1345. dprintf(fd, "\n\n ");
  1346. while (*p) {
  1347. if (*p == ',') {
  1348. *p = '\0';
  1349. dprintf(fd, " %s\n", begin);
  1350. begin = p + 1;
  1351. }
  1352. ++p;
  1353. }
  1354. dprintf(fd, " %s", begin);
  1355. }
  1356. dprintf(fd, "\n\n");
  1357. } else
  1358. dprintf(fd, "\n\n\n");
  1359. close(fd);
  1360. exitcurses();
  1361. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1362. unlink(tmp);
  1363. initcurses();
  1364. return 0;
  1365. }
  1366. static size_t
  1367. get_fs_free(const char *path)
  1368. {
  1369. static struct statvfs svb;
  1370. if (statvfs(path, &svb) == -1)
  1371. return 0;
  1372. else
  1373. return svb.f_bavail << ffs(svb.f_frsize >> 1);
  1374. }
  1375. static size_t
  1376. get_fs_capacity(const char *path)
  1377. {
  1378. struct statvfs svb;
  1379. if (statvfs(path, &svb) == -1)
  1380. return 0;
  1381. else
  1382. return svb.f_blocks << ffs(svb.f_bsize >> 1);
  1383. }
  1384. static int
  1385. show_mediainfo(char *fpath, char *arg)
  1386. {
  1387. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[cfg.metaviewer], NULL, 0))
  1388. return -1;
  1389. exitcurses();
  1390. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, 1);
  1391. initcurses();
  1392. return 0;
  1393. }
  1394. static int
  1395. handle_archive(char *fpath, char *arg, char *dir)
  1396. {
  1397. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[4], NULL, 0))
  1398. return -1;
  1399. if (arg[1] == 'x')
  1400. spawn(utils[4], arg, fpath, dir, F_NORMAL);
  1401. else {
  1402. exitcurses();
  1403. get_output(NULL, 0, utils[4], arg, fpath, 1);
  1404. initcurses();
  1405. }
  1406. return 0;
  1407. }
  1408. /*
  1409. * The help string tokens (each line) start with a HEX value
  1410. * which indicates the number of spaces to print before the
  1411. * particular token. This method was chosen instead of a flat
  1412. * string because the number of bytes in help was increasing
  1413. * the binary size by around a hundred bytes. This would only
  1414. * have increased as we keep adding new options.
  1415. */
  1416. static int
  1417. show_help(char *path)
  1418. {
  1419. char tmp[] = "/tmp/nnnXXXXXX";
  1420. int i = 0, fd = mkstemp(tmp);
  1421. char *start, *end;
  1422. static char helpstr[] = (
  1423. "cKey | Function\n"
  1424. "e- + -\n"
  1425. "7↑, k, ^P | Previous entry\n"
  1426. "7↓, j, ^N | Next entry\n"
  1427. "7PgUp, ^U | Scroll half page up\n"
  1428. "7PgDn, ^D | Scroll half page down\n"
  1429. "1Home, g, ^, ^A | First entry\n"
  1430. "2End, G, $, ^E | Last entry\n"
  1431. "4→, ↵, l, ^M | Open file or enter dir\n"
  1432. "1←, Bksp, h, ^H | Go to parent dir\n"
  1433. "d^O | Open with...\n"
  1434. "9Insert | Toggle navigate-as-you-type\n"
  1435. "e~ | Go HOME\n"
  1436. "e& | Go to initial dir\n"
  1437. "e- | Go to last visited dir\n"
  1438. "e/ | Filter dir contents\n"
  1439. "d^/ | Open desktop search tool\n"
  1440. "e. | Toggle hide . files\n"
  1441. "eb | Bookmark prompt\n"
  1442. "d^B | Pin current dir\n"
  1443. "d^V | Go to pinned dir\n"
  1444. "ec | Change dir prompt\n"
  1445. "ed | Toggle detail view\n"
  1446. "eD | File details\n"
  1447. "em | Brief media info\n"
  1448. "eM | Full media info\n"
  1449. "en | Create new\n"
  1450. "d^R | Rename entry\n"
  1451. "es | Toggle sort by size\n"
  1452. "eS | Toggle du mode\n"
  1453. "et | Toggle sort by mtime\n"
  1454. "e! | Spawn SHELL in dir\n"
  1455. "ee | Edit entry in EDITOR\n"
  1456. "eo | Open dir in file manager\n"
  1457. "ep | Open entry in PAGER\n"
  1458. "eF | List archive\n"
  1459. "d^X | Extract archive\n"
  1460. "d^K | Invoke file path copier\n"
  1461. "d^L | Redraw, clear prompt\n"
  1462. "e? | Help, settings\n"
  1463. "eQ | Quit and cd\n"
  1464. "aq, ^Q | Quit\n\n");
  1465. if (fd == -1)
  1466. return -1;
  1467. start = end = helpstr;
  1468. while (*end) {
  1469. while (*end != '\n')
  1470. ++end;
  1471. if (start == end) {
  1472. ++end;
  1473. continue;
  1474. }
  1475. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1476. start = ++end;
  1477. }
  1478. dprintf(fd, "\n");
  1479. if (getenv("NNN_BMS")) {
  1480. dprintf(fd, "BOOKMARKS\n");
  1481. for (; i < BM_MAX; ++i)
  1482. if (bookmark[i].key)
  1483. dprintf(fd, " %s: %s\n", bookmark[i].key, bookmark[i].loc);
  1484. else
  1485. break;
  1486. dprintf(fd, "\n");
  1487. }
  1488. if (editor)
  1489. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1490. if (desktop_manager)
  1491. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1492. if (idletimeout)
  1493. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1494. if (copier)
  1495. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1496. dprintf(fd, "\nVolume: %s of ", coolsize(get_fs_free(path)));
  1497. dprintf(fd, "%s free\n", coolsize(get_fs_capacity(path)));
  1498. dprintf(fd, "\nVersion: %s\n%s\n", VERSION, GENERAL_INFO);
  1499. close(fd);
  1500. exitcurses();
  1501. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1502. unlink(tmp);
  1503. initcurses();
  1504. return 0;
  1505. }
  1506. static int
  1507. sum_bsizes(const char *fpath, const struct stat *sb,
  1508. int typeflag, struct FTW *ftwbuf)
  1509. {
  1510. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1511. ent_blocks += sb->st_blocks;
  1512. ++num_files;
  1513. return 0;
  1514. }
  1515. static int
  1516. dentfill(char *path, struct entry **dents,
  1517. int (*filter)(regex_t *, char *), regex_t *re)
  1518. {
  1519. static DIR *dirp;
  1520. static struct dirent *dp;
  1521. static char *namep, *pnb;
  1522. static struct entry *dentp;
  1523. static size_t off, namebuflen = NAMEBUF_INCR;
  1524. static ulong num_saved;
  1525. static int fd, n, count;
  1526. static struct stat sb_path, sb;
  1527. off = 0;
  1528. dirp = opendir(path);
  1529. if (dirp == NULL)
  1530. return 0;
  1531. fd = dirfd(dirp);
  1532. n = 0;
  1533. if (cfg.blkorder) {
  1534. num_files = 0;
  1535. dir_blocks = 0;
  1536. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  1537. printwarn();
  1538. return 0;
  1539. }
  1540. }
  1541. while ((dp = readdir(dirp)) != NULL) {
  1542. namep = dp->d_name;
  1543. if (filter(re, namep) == 0) {
  1544. if (!cfg.blkorder)
  1545. continue;
  1546. /* Skip self and parent */
  1547. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  1548. continue;
  1549. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  1550. continue;
  1551. if (S_ISDIR(sb.st_mode)) {
  1552. if (sb_path.st_dev == sb.st_dev) {
  1553. ent_blocks = 0;
  1554. mkpath(path, namep, g_buf, PATH_MAX);
  1555. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1556. printmsg(STR_NFTWFAIL);
  1557. dir_blocks += sb.st_blocks;
  1558. } else
  1559. dir_blocks += ent_blocks;
  1560. }
  1561. } else {
  1562. if (sb.st_blocks)
  1563. dir_blocks += sb.st_blocks;
  1564. ++num_files;
  1565. }
  1566. continue;
  1567. }
  1568. /* Skip self and parent */
  1569. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1570. (namep[1] == '.' && namep[2] == '\0'))))
  1571. continue;
  1572. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1573. DPRINTF_S(namep);
  1574. continue;
  1575. }
  1576. if (n == total_dents) {
  1577. total_dents += ENTRY_INCR;
  1578. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1579. if (*dents == NULL) {
  1580. if (pnamebuf)
  1581. free(pnamebuf);
  1582. errexit();
  1583. }
  1584. }
  1585. /* If there's not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  1586. if (namebuflen - off < NAME_MAX + 1) {
  1587. namebuflen += NAMEBUF_INCR;
  1588. pnb = pnamebuf;
  1589. pnamebuf = (char *)realloc(pnamebuf, namebuflen);
  1590. DPRINTF_P(pnamebuf);
  1591. if (pnamebuf == NULL) {
  1592. free(*dents);
  1593. errexit();
  1594. }
  1595. /* realloc() may result in memory move, we must re-adjust if that happens */
  1596. if (pnb != pnamebuf) {
  1597. dentp = *dents;
  1598. dentp->name = pnamebuf;
  1599. for (count = 1; count < n; ++dentp, ++count)
  1600. /* Current filename starts at last filename start + length */
  1601. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  1602. }
  1603. }
  1604. dentp = *dents + n;
  1605. /* Copy file name */
  1606. dentp->name = (char *)((size_t)pnamebuf + off);
  1607. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  1608. off += dentp->nlen;
  1609. /* Copy other fields */
  1610. dentp->mode = sb.st_mode;
  1611. dentp->t = sb.st_mtime;
  1612. dentp->size = sb.st_size;
  1613. if (cfg.blkorder) {
  1614. if (S_ISDIR(sb.st_mode)) {
  1615. ent_blocks = 0;
  1616. num_saved = num_files + 1;
  1617. mkpath(path, namep, g_buf, PATH_MAX);
  1618. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1619. printmsg(STR_NFTWFAIL);
  1620. dentp->blocks = sb.st_blocks;
  1621. } else
  1622. dentp->blocks = ent_blocks;
  1623. if (sb_path.st_dev == sb.st_dev)
  1624. dir_blocks += dentp->blocks;
  1625. else
  1626. num_files = num_saved;
  1627. } else {
  1628. dentp->blocks = sb.st_blocks;
  1629. dir_blocks += dentp->blocks;
  1630. ++num_files;
  1631. }
  1632. }
  1633. ++n;
  1634. }
  1635. /* Should never be null */
  1636. if (closedir(dirp) == -1) {
  1637. if (*dents) {
  1638. free(pnamebuf);
  1639. free(*dents);
  1640. }
  1641. errexit();
  1642. }
  1643. return n;
  1644. }
  1645. static void
  1646. dentfree(struct entry *dents)
  1647. {
  1648. free(pnamebuf);
  1649. free(dents);
  1650. }
  1651. /* Return the position of the matching entry or 0 otherwise */
  1652. static int
  1653. dentfind(struct entry *dents, const char *fname, int n)
  1654. {
  1655. static int i;
  1656. if (!fname)
  1657. return 0;
  1658. DPRINTF_S(fname);
  1659. for (i = 0; i < n; ++i)
  1660. if (xstrcmp(fname, dents[i].name) == 0)
  1661. return i;
  1662. return 0;
  1663. }
  1664. static int
  1665. populate(char *path, char *oldname, char *fltr)
  1666. {
  1667. static regex_t re;
  1668. /* Can fail when permissions change while browsing.
  1669. * It's assumed that path IS a directory when we are here.
  1670. */
  1671. if (access(path, R_OK) == -1)
  1672. return -1;
  1673. /* Search filter */
  1674. if (setfilter(&re, fltr) != 0)
  1675. return -1;
  1676. if (cfg.blkorder) {
  1677. printmsg("Calculating...");
  1678. refresh();
  1679. }
  1680. #ifdef DEBUGMODE
  1681. struct timespec ts1, ts2;
  1682. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  1683. #endif
  1684. ndents = dentfill(path, &dents, visible, &re);
  1685. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1686. #ifdef DEBUGMODE
  1687. clock_gettime(CLOCK_REALTIME, &ts2);
  1688. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  1689. #endif
  1690. /* Find cur from history */
  1691. cur = dentfind(dents, oldname, ndents);
  1692. regfree(&re);
  1693. return 0;
  1694. }
  1695. static void
  1696. redraw(char *path)
  1697. {
  1698. static char buf[(NAME_MAX + 1) << 1];
  1699. static size_t ncols;
  1700. static int nlines, i;
  1701. static bool mode_changed;
  1702. mode_changed = FALSE;
  1703. nlines = MIN(LINES - 4, ndents);
  1704. /* Clean screen */
  1705. erase();
  1706. /* Fail redraw if < than 10 columns */
  1707. if (COLS < 10) {
  1708. printmsg("Too few columns!");
  1709. return;
  1710. }
  1711. /* Strip trailing slashes */
  1712. for (i = xstrlen(path) - 1; i > 0; --i)
  1713. if (path[i] == '/')
  1714. path[i] = '\0';
  1715. else
  1716. break;
  1717. DPRINTF_D(cur);
  1718. DPRINTF_S(path);
  1719. if (!realpath(path, g_buf)) {
  1720. printwarn();
  1721. return;
  1722. }
  1723. ncols = COLS;
  1724. if (ncols > PATH_MAX)
  1725. ncols = PATH_MAX;
  1726. /* No text wrapping in cwd line */
  1727. /* Show CWD: - xstrlen(CWD) - 1 = 6 */
  1728. g_buf[ncols - 6] = '\0';
  1729. printw(CWD "%s\n\n", g_buf);
  1730. /* Fallback to light mode if less than 35 columns */
  1731. if (ncols < 35 && cfg.showdetail) {
  1732. cfg.showdetail ^= 1;
  1733. printptr = &printent;
  1734. mode_changed = TRUE;
  1735. }
  1736. /* Calculate the number of cols available to print entry name */
  1737. if (cfg.showdetail)
  1738. ncols -= 32;
  1739. else
  1740. ncols -= 5;
  1741. if (cfg.showcolor) {
  1742. attron(COLOR_PAIR(1) | A_BOLD);
  1743. cfg.dircolor = 1;
  1744. }
  1745. /* Print listing */
  1746. if (cur < (nlines >> 1)) {
  1747. for (i = 0; i < nlines; ++i)
  1748. printptr(&dents[i], i == cur, ncols);
  1749. } else if (cur >= ndents - (nlines >> 1)) {
  1750. for (i = ndents - nlines; i < ndents; ++i)
  1751. printptr(&dents[i], i == cur, ncols);
  1752. } else {
  1753. static int odd;
  1754. odd = ISODD(nlines);
  1755. nlines >>= 1;
  1756. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1757. printptr(&dents[i], i == cur, ncols);
  1758. }
  1759. /* Must reset e.g. no files in dir */
  1760. if (cfg.dircolor) {
  1761. attroff(COLOR_PAIR(1) | A_BOLD);
  1762. cfg.dircolor = 0;
  1763. }
  1764. if (cfg.showdetail) {
  1765. if (ndents) {
  1766. static char ind[2] = "\0\0";
  1767. static char sort[9];
  1768. if (cfg.mtimeorder)
  1769. xstrlcpy(sort, "by time ", 9);
  1770. else if (cfg.sizeorder)
  1771. xstrlcpy(sort, "by size ", 9);
  1772. else
  1773. sort[0] = '\0';
  1774. if (S_ISDIR(dents[cur].mode))
  1775. ind[0] = '/';
  1776. else if (S_ISLNK(dents[cur].mode))
  1777. ind[0] = '@';
  1778. else if (S_ISSOCK(dents[cur].mode))
  1779. ind[0] = '=';
  1780. else if (S_ISFIFO(dents[cur].mode))
  1781. ind[0] = '|';
  1782. else if (dents[cur].mode & 0100)
  1783. ind[0] = '*';
  1784. else
  1785. ind[0] = '\0';
  1786. /* We need to show filename as it may be truncated in directory listing */
  1787. if (!cfg.blkorder)
  1788. sprintf(buf, "%d/%d %s[%s%s]", cur + 1, ndents, sort, unescape(dents[cur].name, 0), ind);
  1789. else {
  1790. i = sprintf(buf, "%d/%d du: %s (%lu files) ", cur + 1, ndents, coolsize(dir_blocks << 9), num_files);
  1791. sprintf(buf + i, "vol: %s free [%s%s]", coolsize(get_fs_free(path)), unescape(dents[cur].name, 0), ind);
  1792. }
  1793. printmsg(buf);
  1794. } else
  1795. printmsg("0 items");
  1796. }
  1797. if (mode_changed) {
  1798. cfg.showdetail ^= 1;
  1799. printptr = &printent_long;
  1800. }
  1801. }
  1802. static void
  1803. browse(char *ipath, char *ifilter)
  1804. {
  1805. static char path[PATH_MAX], newpath[PATH_MAX], lastdir[PATH_MAX], mark[PATH_MAX];
  1806. static char fltr[NAME_MAX + 1];
  1807. static char oldname[NAME_MAX + 1];
  1808. char *dir, *tmp, *run = NULL, *env = NULL;
  1809. struct stat sb;
  1810. int r, fd, presel;
  1811. enum action sel = SEL_RUNARG + 1;
  1812. bool dir_changed = FALSE;
  1813. xstrlcpy(path, ipath, PATH_MAX);
  1814. copyfilter();
  1815. oldname[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  1816. if (cfg.filtermode)
  1817. presel = FILTER;
  1818. else
  1819. presel = 0;
  1820. /* Allocate buffer to hold names */
  1821. pnamebuf = (char *)malloc(NAMEBUF_INCR);
  1822. if (pnamebuf == NULL)
  1823. errexit();
  1824. begin:
  1825. #ifdef LINUX_INOTIFY
  1826. if (dir_changed && inotify_wd >= 0) {
  1827. inotify_rm_watch(inotify_fd, inotify_wd);
  1828. inotify_wd = -1;
  1829. dir_changed = FALSE;
  1830. }
  1831. #elif defined(BSD_KQUEUE)
  1832. if (dir_changed && event_fd >= 0) {
  1833. close(event_fd);
  1834. event_fd = -1;
  1835. dir_changed = FALSE;
  1836. }
  1837. #endif
  1838. if (populate(path, oldname, fltr) == -1) {
  1839. printwarn();
  1840. goto nochange;
  1841. }
  1842. #ifdef LINUX_INOTIFY
  1843. if (inotify_wd == -1)
  1844. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  1845. #elif defined(BSD_KQUEUE)
  1846. if (event_fd == -1) {
  1847. #if defined(O_EVTONLY)
  1848. event_fd = open(path, O_EVTONLY);
  1849. #else
  1850. event_fd = open(path, O_RDONLY);
  1851. #endif
  1852. if (event_fd >= 0)
  1853. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  1854. }
  1855. #endif
  1856. for (;;) {
  1857. redraw(path);
  1858. nochange:
  1859. /* Exit if parent has exited */
  1860. if (getppid() == 1)
  1861. _exit(0);
  1862. sel = nextsel(&run, &env, &presel);
  1863. switch (sel) {
  1864. case SEL_BACK:
  1865. /* There is no going back */
  1866. if (istopdir(path)) {
  1867. printmsg(STR_ATROOT);
  1868. goto nochange;
  1869. }
  1870. dir = xdirname(path);
  1871. if (access(dir, R_OK) == -1) {
  1872. printwarn();
  1873. goto nochange;
  1874. }
  1875. /* Save history */
  1876. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  1877. /* Save last working directory */
  1878. xstrlcpy(lastdir, path, PATH_MAX);
  1879. dir_changed = TRUE;
  1880. xstrlcpy(path, dir, PATH_MAX);
  1881. /* Reset filter */
  1882. copyfilter();
  1883. if (cfg.filtermode)
  1884. presel = FILTER;
  1885. goto begin;
  1886. case SEL_GOIN:
  1887. /* Cannot descend in empty directories */
  1888. if (ndents == 0)
  1889. goto begin;
  1890. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1891. DPRINTF_S(newpath);
  1892. /* Get path info */
  1893. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1894. if (fd == -1) {
  1895. printwarn();
  1896. goto nochange;
  1897. }
  1898. if (fstat(fd, &sb) == -1) {
  1899. printwarn();
  1900. close(fd);
  1901. goto nochange;
  1902. }
  1903. close(fd);
  1904. DPRINTF_U(sb.st_mode);
  1905. switch (sb.st_mode & S_IFMT) {
  1906. case S_IFDIR:
  1907. if (access(newpath, R_OK) == -1) {
  1908. printwarn();
  1909. goto nochange;
  1910. }
  1911. /* Save last working directory */
  1912. xstrlcpy(lastdir, path, PATH_MAX);
  1913. dir_changed = TRUE;
  1914. xstrlcpy(path, newpath, PATH_MAX);
  1915. oldname[0] = '\0';
  1916. /* Reset filter */
  1917. copyfilter();
  1918. if (cfg.filtermode)
  1919. presel = FILTER;
  1920. goto begin;
  1921. case S_IFREG:
  1922. {
  1923. /* If NNN_USE_EDITOR is set,
  1924. * open text in EDITOR
  1925. */
  1926. if (editor) {
  1927. if (getmime(dents[cur].name)) {
  1928. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1929. continue;
  1930. }
  1931. /* Recognize and open plain
  1932. * text files with vi
  1933. */
  1934. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  1935. continue;
  1936. if (strstr(g_buf, "text/") == g_buf) {
  1937. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1938. continue;
  1939. }
  1940. }
  1941. /* Invoke desktop opener as last resort */
  1942. spawn(utils[2], newpath, NULL, NULL, nowait);
  1943. continue;
  1944. }
  1945. default:
  1946. printmsg("Unsupported file");
  1947. goto nochange;
  1948. }
  1949. case SEL_NEXT:
  1950. if (cur < ndents - 1)
  1951. ++cur;
  1952. else if (ndents)
  1953. /* Roll over, set cursor to first entry */
  1954. cur = 0;
  1955. break;
  1956. case SEL_PREV:
  1957. if (cur > 0)
  1958. --cur;
  1959. else if (ndents)
  1960. /* Roll over, set cursor to last entry */
  1961. cur = ndents - 1;
  1962. break;
  1963. case SEL_PGDN:
  1964. if (cur < ndents - 1)
  1965. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1966. break;
  1967. case SEL_PGUP:
  1968. if (cur > 0)
  1969. cur -= MIN((LINES - 4) / 2, cur);
  1970. break;
  1971. case SEL_HOME:
  1972. cur = 0;
  1973. break;
  1974. case SEL_END:
  1975. cur = ndents - 1;
  1976. break;
  1977. case SEL_CD:
  1978. {
  1979. char *input;
  1980. int truecd;
  1981. /* Save the program start dir */
  1982. tmp = getcwd(newpath, PATH_MAX);
  1983. if (tmp == NULL) {
  1984. printwarn();
  1985. goto nochange;
  1986. }
  1987. /* Switch to current path for readline(3) */
  1988. if (chdir(path) == -1) {
  1989. printwarn();
  1990. goto nochange;
  1991. }
  1992. exitcurses();
  1993. tmp = readline("chdir: ");
  1994. initcurses();
  1995. /* Change back to program start dir */
  1996. if (chdir(newpath) == -1)
  1997. printwarn();
  1998. if (tmp[0] == '\0')
  1999. break;
  2000. /* Add to readline(3) history */
  2001. add_history(tmp);
  2002. input = tmp;
  2003. tmp = strstrip(tmp);
  2004. if (tmp[0] == '\0') {
  2005. free(input);
  2006. break;
  2007. }
  2008. truecd = 0;
  2009. if (tmp[0] == '~') {
  2010. /* Expand ~ to HOME absolute path */
  2011. char *home = getenv("HOME");
  2012. if (home)
  2013. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  2014. else {
  2015. free(input);
  2016. printmsg(STR_NOHOME);
  2017. goto nochange;
  2018. }
  2019. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  2020. if (lastdir[0] == '\0') {
  2021. free(input);
  2022. break;
  2023. }
  2024. /* Switch to last visited dir */
  2025. xstrlcpy(newpath, lastdir, PATH_MAX);
  2026. truecd = 1;
  2027. } else if ((r = all_dots(tmp))) {
  2028. if (r == 1) {
  2029. /* Always in the current dir */
  2030. free(input);
  2031. break;
  2032. }
  2033. /* Show a message if already at / */
  2034. if (istopdir(path)) {
  2035. printmsg(STR_ATROOT);
  2036. free(input);
  2037. goto nochange;
  2038. }
  2039. --r; /* One . for the current dir */
  2040. dir = path;
  2041. /* Note: fd is used as a tmp variable here */
  2042. for (fd = 0; fd < r; ++fd) {
  2043. /* Reached / ? */
  2044. if (istopdir(path)) {
  2045. /* Can't cd beyond / */
  2046. break;
  2047. }
  2048. dir = xdirname(dir);
  2049. if (access(dir, R_OK) == -1) {
  2050. printwarn();
  2051. free(input);
  2052. goto nochange;
  2053. }
  2054. }
  2055. truecd = 1;
  2056. /* Save the path in case of cd ..
  2057. * We mark the current dir in parent dir
  2058. */
  2059. if (r == 1) {
  2060. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2061. truecd = 2;
  2062. }
  2063. xstrlcpy(newpath, dir, PATH_MAX);
  2064. } else
  2065. mkpath(path, tmp, newpath, PATH_MAX);
  2066. free(input);
  2067. if (!xdiraccess(newpath))
  2068. goto nochange;
  2069. if (truecd == 0) {
  2070. /* Probable change in dir */
  2071. /* No-op if it's the same directory */
  2072. if (xstrcmp(path, newpath) == 0)
  2073. break;
  2074. oldname[0] = '\0';
  2075. } else if (truecd == 1)
  2076. /* Sure change in dir */
  2077. oldname[0] = '\0';
  2078. /* Save last working directory */
  2079. xstrlcpy(lastdir, path, PATH_MAX);
  2080. dir_changed = TRUE;
  2081. /* Save the newly opted dir in path */
  2082. xstrlcpy(path, newpath, PATH_MAX);
  2083. /* Reset filter */
  2084. copyfilter();
  2085. DPRINTF_S(path);
  2086. if (cfg.filtermode)
  2087. presel = FILTER;
  2088. goto begin;
  2089. }
  2090. case SEL_CDHOME:
  2091. dir = getenv("HOME");
  2092. if (dir == NULL) {
  2093. clearprompt();
  2094. goto nochange;
  2095. } // fallthrough
  2096. case SEL_CDBEGIN:
  2097. if (sel == SEL_CDBEGIN)
  2098. dir = ipath;
  2099. if (!xdiraccess(dir)) {
  2100. goto nochange;
  2101. }
  2102. if (xstrcmp(path, dir) == 0) {
  2103. break;
  2104. }
  2105. /* Save last working directory */
  2106. xstrlcpy(lastdir, path, PATH_MAX);
  2107. dir_changed = TRUE;
  2108. xstrlcpy(path, dir, PATH_MAX);
  2109. oldname[0] = '\0';
  2110. /* Reset filter */
  2111. copyfilter();
  2112. DPRINTF_S(path);
  2113. if (cfg.filtermode)
  2114. presel = FILTER;
  2115. goto begin;
  2116. case SEL_CDLAST: // fallthrough
  2117. case SEL_VISIT:
  2118. if (sel == SEL_VISIT) {
  2119. if (xstrcmp(mark, path) == 0)
  2120. break;
  2121. tmp = mark;
  2122. } else
  2123. tmp = lastdir;
  2124. if (tmp[0] == '\0') {
  2125. printmsg("Not set...");
  2126. goto nochange;
  2127. }
  2128. if (!xdiraccess(tmp))
  2129. goto nochange;
  2130. xstrlcpy(newpath, tmp, PATH_MAX);
  2131. xstrlcpy(lastdir, path, PATH_MAX);
  2132. dir_changed = TRUE;
  2133. xstrlcpy(path, newpath, PATH_MAX);
  2134. oldname[0] = '\0';
  2135. /* Reset filter */
  2136. copyfilter();
  2137. DPRINTF_S(path);
  2138. if (cfg.filtermode)
  2139. presel = FILTER;
  2140. goto begin;
  2141. case SEL_CDBM:
  2142. printprompt("key: ");
  2143. tmp = readinput();
  2144. clearprompt();
  2145. if (tmp == NULL)
  2146. break;
  2147. if (get_bm_loc(tmp, newpath) == NULL) {
  2148. printmsg(STR_INVBM);
  2149. goto nochange;
  2150. }
  2151. if (!xdiraccess(newpath))
  2152. goto nochange;
  2153. if (xstrcmp(path, newpath) == 0)
  2154. break;
  2155. oldname[0] = '\0';
  2156. /* Save last working directory */
  2157. xstrlcpy(lastdir, path, PATH_MAX);
  2158. dir_changed = TRUE;
  2159. /* Save the newly opted dir in path */
  2160. xstrlcpy(path, newpath, PATH_MAX);
  2161. /* Reset filter */
  2162. copyfilter();
  2163. DPRINTF_S(path);
  2164. if (cfg.filtermode)
  2165. presel = FILTER;
  2166. goto begin;
  2167. case SEL_PIN:
  2168. xstrlcpy(mark, path, PATH_MAX);
  2169. printmsg(mark);
  2170. goto nochange;
  2171. case SEL_FLTR:
  2172. presel = filterentries(path);
  2173. copyfilter();
  2174. DPRINTF_S(fltr);
  2175. /* Save current */
  2176. if (ndents > 0)
  2177. copycurname();
  2178. goto nochange;
  2179. case SEL_MFLTR:
  2180. cfg.filtermode ^= 1;
  2181. if (cfg.filtermode)
  2182. presel = FILTER;
  2183. else
  2184. printmsg("navigate-as-you-type off");
  2185. goto nochange;
  2186. case SEL_SEARCH:
  2187. spawn(player, path, "search", NULL, F_NORMAL);
  2188. break;
  2189. case SEL_TOGGLEDOT:
  2190. cfg.showhidden ^= 1;
  2191. initfilter(cfg.showhidden, &ifilter);
  2192. copyfilter();
  2193. goto begin;
  2194. case SEL_DETAIL:
  2195. cfg.showdetail ^= 1;
  2196. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2197. /* Save current */
  2198. if (ndents > 0)
  2199. copycurname();
  2200. goto begin;
  2201. case SEL_STATS:
  2202. if (ndents > 0) {
  2203. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2204. if (lstat(newpath, &sb) == -1) {
  2205. if (dents)
  2206. dentfree(dents);
  2207. errexit();
  2208. } else {
  2209. if (show_stats(newpath, dents[cur].name, &sb) < 0) {
  2210. printwarn();
  2211. goto nochange;
  2212. }
  2213. }
  2214. }
  2215. break;
  2216. case SEL_LIST: // fallthrough
  2217. case SEL_EXTRACT: // fallthrough
  2218. case SEL_MEDIA: // fallthrough
  2219. case SEL_FMEDIA:
  2220. if (ndents > 0) {
  2221. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2222. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2223. r = show_mediainfo(newpath, run);
  2224. else
  2225. r = handle_archive(newpath, run, path);
  2226. if (r == -1) {
  2227. xstrlcpy(newpath, "missing ", PATH_MAX);
  2228. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2229. xstrlcpy(newpath + 8, utils[cfg.metaviewer], 32);
  2230. else
  2231. xstrlcpy(newpath + 8, utils[4], 32);
  2232. printmsg(newpath);
  2233. goto nochange;
  2234. }
  2235. }
  2236. break;
  2237. case SEL_DFB:
  2238. if (!desktop_manager) {
  2239. printmsg("NNN_DE_FILE_MANAGER not set");
  2240. goto nochange;
  2241. }
  2242. spawn(desktop_manager, path, NULL, path, F_NOTRACE | F_NOWAIT);
  2243. break;
  2244. case SEL_FSIZE:
  2245. cfg.sizeorder ^= 1;
  2246. cfg.mtimeorder = 0;
  2247. cfg.blkorder = 0;
  2248. /* Save current */
  2249. if (ndents > 0)
  2250. copycurname();
  2251. goto begin;
  2252. case SEL_BSIZE:
  2253. cfg.blkorder ^= 1;
  2254. if (cfg.blkorder) {
  2255. cfg.showdetail = 1;
  2256. printptr = &printent_long;
  2257. }
  2258. cfg.mtimeorder = 0;
  2259. cfg.sizeorder = 0;
  2260. /* Save current */
  2261. if (ndents > 0)
  2262. copycurname();
  2263. goto begin;
  2264. case SEL_MTIME:
  2265. cfg.mtimeorder ^= 1;
  2266. cfg.sizeorder = 0;
  2267. cfg.blkorder = 0;
  2268. /* Save current */
  2269. if (ndents > 0)
  2270. copycurname();
  2271. goto begin;
  2272. case SEL_REDRAW:
  2273. /* Save current */
  2274. if (ndents > 0)
  2275. copycurname();
  2276. goto begin;
  2277. case SEL_COPY:
  2278. if (copier && ndents) {
  2279. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2280. spawn(copier, newpath, NULL, NULL, F_NONE);
  2281. printmsg(newpath);
  2282. } else if (!copier)
  2283. printmsg("NNN_COPIER is not set");
  2284. goto nochange;
  2285. case SEL_OPEN:
  2286. printprompt("open with: "); // fallthrough
  2287. case SEL_NEW:
  2288. if (sel == SEL_NEW)
  2289. printprompt("name: ");
  2290. tmp = xreadline(NULL);
  2291. clearprompt();
  2292. if (tmp == NULL || tmp[0] == '\0')
  2293. break;
  2294. /* Allow only relative, same dir paths */
  2295. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  2296. printmsg(STR_INPUT);
  2297. goto nochange;
  2298. }
  2299. if (sel == SEL_OPEN) {
  2300. printprompt("Press 'c' for cli mode");
  2301. cleartimeout();
  2302. r = getch();
  2303. settimeout();
  2304. if (r == 'c')
  2305. r = F_NORMAL;
  2306. else
  2307. r = F_NOWAIT;
  2308. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2309. spawn(tmp, newpath, NULL, path, r);
  2310. continue;
  2311. }
  2312. /* Open the descriptor to currently open directory */
  2313. fd = open(path, O_RDONLY | O_DIRECTORY);
  2314. if (fd == -1) {
  2315. printwarn();
  2316. goto nochange;
  2317. }
  2318. /* Check if another file with same name exists */
  2319. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2320. printmsg("Entry exists");
  2321. goto nochange;
  2322. }
  2323. /* Check if it's a dir or file */
  2324. printprompt("Press 'f' for file or 'd' for dir");
  2325. cleartimeout();
  2326. r = getch();
  2327. settimeout();
  2328. if (r == 'f') {
  2329. r = openat(fd, tmp, O_CREAT, 0666);
  2330. close(r);
  2331. } else if (r == 'd')
  2332. r = mkdirat(fd, tmp, 0777);
  2333. else {
  2334. close(fd);
  2335. break;
  2336. }
  2337. if (r == -1) {
  2338. printwarn();
  2339. close(fd);
  2340. goto nochange;
  2341. }
  2342. close(fd);
  2343. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2344. goto begin;
  2345. case SEL_RENAME:
  2346. if (ndents <= 0)
  2347. break;
  2348. printprompt("");
  2349. tmp = xreadline(dents[cur].name);
  2350. clearprompt();
  2351. if (tmp == NULL || tmp[0] == '\0')
  2352. break;
  2353. /* Allow only relative, same dir paths */
  2354. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  2355. printmsg(STR_INPUT);
  2356. goto nochange;
  2357. }
  2358. /* Skip renaming to same name */
  2359. if (xstrcmp(tmp, dents[cur].name) == 0)
  2360. break;
  2361. /* Open the descriptor to currently open directory */
  2362. fd = open(path, O_RDONLY | O_DIRECTORY);
  2363. if (fd == -1) {
  2364. printwarn();
  2365. goto nochange;
  2366. }
  2367. /* Check if another file with same name exists */
  2368. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2369. /* File with the same name exists */
  2370. printprompt("Press 'y' to overwrite");
  2371. cleartimeout();
  2372. r = getch();
  2373. settimeout();
  2374. if (r != 'y') {
  2375. close(fd);
  2376. break;
  2377. }
  2378. }
  2379. /* Rename the file */
  2380. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  2381. printwarn();
  2382. close(fd);
  2383. goto nochange;
  2384. }
  2385. close(fd);
  2386. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2387. goto begin;
  2388. case SEL_HELP:
  2389. show_help(path);
  2390. break;
  2391. case SEL_RUN:
  2392. run = xgetenv(env, run);
  2393. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2394. /* Repopulate as directory content may have changed */
  2395. goto begin;
  2396. case SEL_RUNARG:
  2397. run = xgetenv(env, run);
  2398. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2399. break;
  2400. case SEL_CDQUIT:
  2401. {
  2402. char *tmpfile = "/tmp/nnn";
  2403. tmp = getenv("NNN_TMPFILE");
  2404. if (tmp)
  2405. tmpfile = tmp;
  2406. FILE *fp = fopen(tmpfile, "w");
  2407. if (fp) {
  2408. fprintf(fp, "cd \"%s\"", path);
  2409. fclose(fp);
  2410. }
  2411. /* Fall through to exit */
  2412. } // fallthrough
  2413. case SEL_QUIT:
  2414. dentfree(dents);
  2415. return;
  2416. }
  2417. /* Screensaver */
  2418. if (idletimeout != 0 && idle == idletimeout) {
  2419. idle = 0;
  2420. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2421. }
  2422. }
  2423. }
  2424. static void
  2425. usage(void)
  2426. {
  2427. printf("usage: nnn [-b key] [-c N] [-e] [-i] [-l]\n\
  2428. [-p nlay] [-S] [-v] [-h] [PATH]\n\n\
  2429. The missing terminal file browser for X.\n\n\
  2430. positional arguments:\n\
  2431. PATH start dir [default: current dir]\n\n\
  2432. optional arguments:\n\
  2433. -b key specify bookmark key to open\n\
  2434. -c N specify dir color, disables if N>7\n\
  2435. -e use exiftool instead of mediainfo\n\
  2436. -i start in navigate-as-you-type mode\n\
  2437. -l start in light mode (fewer details)\n\
  2438. -p nlay path to custom nlay\n\
  2439. -S start in disk usage analyzer mode\n\
  2440. -v show program version and exit\n\
  2441. -h show this help and exit\n\n\
  2442. Version: %s\n%s\n", VERSION, GENERAL_INFO);
  2443. exit(0);
  2444. }
  2445. int
  2446. main(int argc, char *argv[])
  2447. {
  2448. static char cwd[PATH_MAX];
  2449. char *ipath = NULL, *ifilter, *bmstr;
  2450. int opt;
  2451. /* Confirm we are in a terminal */
  2452. if (!isatty(0) || !isatty(1)) {
  2453. fprintf(stderr, "stdin or stdout is not a tty\n");
  2454. exit(1);
  2455. }
  2456. while ((opt = getopt(argc, argv, "Slib:c:ep:vh")) != -1) {
  2457. switch (opt) {
  2458. case 'S':
  2459. cfg.blkorder = 1;
  2460. break;
  2461. case 'l':
  2462. cfg.showdetail = 0;
  2463. printptr = &printent;
  2464. break;
  2465. case 'i':
  2466. cfg.filtermode = 1;
  2467. break;
  2468. case 'b':
  2469. ipath = optarg;
  2470. break;
  2471. case 'c':
  2472. if (atoi(optarg) > 7)
  2473. cfg.showcolor = 0;
  2474. else
  2475. cfg.color = (uchar)atoi(optarg);
  2476. break;
  2477. case 'e':
  2478. cfg.metaviewer = 1;
  2479. break;
  2480. case 'p':
  2481. player = optarg;
  2482. break;
  2483. case 'v':
  2484. printf("%s\n", VERSION);
  2485. return 0;
  2486. case 'h': // fallthrough
  2487. default:
  2488. usage();
  2489. }
  2490. }
  2491. /* Parse bookmarks string, if available */
  2492. bmstr = getenv("NNN_BMS");
  2493. if (bmstr)
  2494. parsebmstr(bmstr);
  2495. if (ipath) { /* Open a bookmark directly */
  2496. if (get_bm_loc(ipath, cwd) == NULL) {
  2497. fprintf(stderr, "%s\n", STR_INVBM);
  2498. exit(1);
  2499. }
  2500. ipath = cwd;
  2501. } else if (argc == optind) {
  2502. /* Start in the current directory */
  2503. ipath = getcwd(cwd, PATH_MAX);
  2504. if (ipath == NULL)
  2505. ipath = "/";
  2506. } else {
  2507. ipath = realpath(argv[optind], cwd);
  2508. if (!ipath) {
  2509. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2510. exit(1);
  2511. }
  2512. }
  2513. /* Increase current open file descriptor limit */
  2514. open_max = max_openfds();
  2515. if (getuid() == 0)
  2516. cfg.showhidden = 1;
  2517. initfilter(cfg.showhidden, &ifilter);
  2518. #ifdef LINUX_INOTIFY
  2519. /* Initialize inotify */
  2520. inotify_fd = inotify_init1(IN_NONBLOCK);
  2521. if (inotify_fd < 0) {
  2522. fprintf(stderr, "inotify init! %s\n", strerror(errno));
  2523. exit(1);
  2524. }
  2525. #elif defined(BSD_KQUEUE)
  2526. kq = kqueue();
  2527. if (kq < 0) {
  2528. fprintf(stderr, "kqueue init! %s\n", strerror(errno));
  2529. exit(1);
  2530. }
  2531. gtimeout.tv_sec = 0;
  2532. gtimeout.tv_nsec = 0;
  2533. #endif
  2534. /* Edit text in EDITOR, if opted */
  2535. if (getenv("NNN_USE_EDITOR"))
  2536. editor = xgetenv("EDITOR", "vi");
  2537. /* Set player if not set already */
  2538. if (!player)
  2539. player = utils[3];
  2540. /* Get the desktop file browser, if set */
  2541. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2542. /* Get screensaver wait time, if set; copier used as tmp var */
  2543. copier = getenv("NNN_IDLE_TIMEOUT");
  2544. if (copier)
  2545. idletimeout = abs(atoi(copier));
  2546. /* Get the default copier, if set */
  2547. copier = getenv("NNN_COPIER");
  2548. /* Get nowait flag */
  2549. nowait |= getenv("NNN_NOWAIT") ? F_NOWAIT : 0;
  2550. signal(SIGINT, SIG_IGN);
  2551. /* Test initial path */
  2552. if (!xdiraccess(ipath)) {
  2553. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2554. exit(1);
  2555. }
  2556. /* Set locale */
  2557. setlocale(LC_ALL, "");
  2558. #ifdef DEBUGMODE
  2559. enabledbg();
  2560. #endif
  2561. initcurses();
  2562. browse(ipath, ifilter);
  2563. exitcurses();
  2564. #ifdef LINUX_INOTIFY
  2565. /* Shutdown inotify */
  2566. if (inotify_wd >= 0)
  2567. inotify_rm_watch(inotify_fd, inotify_wd);
  2568. close(inotify_fd);
  2569. #elif defined(BSD_KQUEUE)
  2570. if (event_fd >= 0)
  2571. close(event_fd);
  2572. close(kq);
  2573. #endif
  2574. #ifdef DEBUGMODE
  2575. disabledbg();
  2576. #endif
  2577. exit(0);
  2578. }