My build of nnn with minor changes
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

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