My build of nnn with minor changes
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

2811 Zeilen
58 KiB

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