My build of nnn with minor changes
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

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