My build of nnn with minor changes
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

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