My build of nnn with minor changes
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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