My build of nnn with minor changes
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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