My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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