My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

3004 lines
63 KiB

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