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

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