My build of nnn with minor changes
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

2966 рядки
61 KiB

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