My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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