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

2903 satır
60 KiB

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