My build of nnn with minor changes
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

2845 satır
58 KiB

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