My build of nnn with minor changes
 
 
 
 
 
 

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