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.
 
 
 
 
 
 

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