My build of nnn with minor changes
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

2826 linhas
58 KiB

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