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.
 
 
 
 
 
 

2715 satır
56 KiB

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