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

3018 satır
63 KiB

  1. /* See LICENSE file for copyright and license details. */
  2. /*
  3. * Visual layout:
  4. * .---------
  5. * | DIR: /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 "DIR: "
  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 copyfilter() xstrlcpy(fltr, ifilter, NAME_MAX)
  157. #define copycurname() xstrlcpy(oldname, dents[cur].name, NAME_MAX + 1)
  158. #define settimeout() timeout(1000)
  159. #define cleartimeout() timeout(-1)
  160. #define errexit() printerr(__LINE__)
  161. #ifdef LINUX_INOTIFY
  162. #define EVENT_SIZE (sizeof(struct inotify_event))
  163. #define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
  164. #elif defined(BSD_KQUEUE)
  165. #define NUM_EVENT_SLOTS 1
  166. #define NUM_EVENT_FDS 1
  167. #endif
  168. /* TYPE DEFINITIONS */
  169. typedef unsigned long ulong;
  170. typedef unsigned int uint;
  171. typedef unsigned char uchar;
  172. /* STRUCTURES */
  173. /* Directory entry */
  174. typedef struct entry {
  175. char *name;
  176. time_t t;
  177. off_t size;
  178. blkcnt_t blocks; /* number of 512B blocks allocated */
  179. mode_t mode;
  180. uint nlen; /* Length of file name; can be uchar (< NAME_MAX + 1) */
  181. } *pEntry;
  182. /* Bookmark */
  183. typedef struct {
  184. char *key;
  185. char *loc;
  186. } bm;
  187. /* Settings */
  188. typedef struct {
  189. ushort filtermode : 1; /* Set to enter filter mode */
  190. ushort mtimeorder : 1; /* Set to sort by time modified */
  191. ushort sizeorder : 1; /* Set to sort by file size */
  192. ushort blkorder : 1; /* Set to sort by blocks used (disk usage) */
  193. ushort showhidden : 1; /* Set to show hidden files */
  194. ushort showdetail : 1; /* Clear to show fewer file info */
  195. ushort showcolor : 1; /* Set to show dirs in blue */
  196. ushort dircolor : 1; /* Current status of dir color */
  197. ushort metaviewer : 1; /* Index of metadata viewer in utils[] */
  198. ushort color : 3; /* Color code for directories */
  199. } settings;
  200. /* GLOBALS */
  201. /* Configuration */
  202. static settings cfg = {0, 0, 0, 0, 0, 1, 1, 0, 0, 4};
  203. static struct entry *dents;
  204. static char *pnamebuf;
  205. static int ndents, cur, total_dents;
  206. static uint idle;
  207. static uint idletimeout;
  208. static char *player;
  209. static char *copier;
  210. static char *editor;
  211. static char *desktop_manager;
  212. static char nowait = F_NOTRACE;
  213. static blkcnt_t ent_blocks;
  214. static blkcnt_t dir_blocks;
  215. static ulong num_files;
  216. static uint open_max;
  217. static bm bookmark[BM_MAX];
  218. #ifdef LINUX_INOTIFY
  219. static int inotify_fd, inotify_wd = -1;
  220. static uint INOTIFY_MASK = IN_ATTRIB | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  221. #elif defined(BSD_KQUEUE)
  222. static int kq, event_fd = -1;
  223. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  224. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  225. static struct timespec gtimeout;
  226. #endif
  227. /* Utilities to open files, run actions */
  228. static char * const utils[] = {
  229. "mediainfo",
  230. "exiftool",
  231. #ifdef __APPLE__
  232. "/usr/bin/open",
  233. #else
  234. "/usr/bin/xdg-open",
  235. #endif
  236. "nlay",
  237. "atool"
  238. };
  239. /* Common message strings */
  240. static const char *STR_NFTWFAIL = "nftw(3) failed";
  241. static const char *STR_ATROOT = "You are at /";
  242. static const char *STR_NOHOME = "HOME not set";
  243. static const char *STR_INPUT = "No traversal delimiter allowed";
  244. static const char *STR_INVBM = "Invalid bookmark";
  245. /* For use in functions which are isolated and don't return the buffer */
  246. static char g_buf[MAX_CMD_LEN];
  247. /* Forward declarations */
  248. static void redraw(char *path);
  249. /* Functions */
  250. /* Messages show up at the bottom */
  251. static void
  252. printmsg(const char *msg)
  253. {
  254. mvprintw(LINES - 1, 0, "%s\n", msg);
  255. }
  256. /* Kill curses and display error before exiting */
  257. static void
  258. printerr(int linenum)
  259. {
  260. exitcurses();
  261. fprintf(stderr, "line %d: (%d) %s\n", linenum, errno, strerror(errno));
  262. exit(1);
  263. }
  264. /* Print prompt on the last line */
  265. static void
  266. printprompt(char *str)
  267. {
  268. clearprompt();
  269. printw(str);
  270. }
  271. /* Increase the limit on open file descriptors, if possible */
  272. static rlim_t
  273. max_openfds()
  274. {
  275. struct rlimit rl;
  276. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  277. if (limit != 0)
  278. return 32;
  279. limit = rl.rlim_cur;
  280. rl.rlim_cur = rl.rlim_max;
  281. /* Return ~75% of max possible */
  282. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  283. limit = rl.rlim_max - (rl.rlim_max >> 2);
  284. /*
  285. * 20K is arbitrary. If the limit is set to max possible
  286. * value, the memory usage increases to more than double.
  287. */
  288. return limit > 20480 ? 20480 : limit;
  289. }
  290. return limit;
  291. }
  292. /*
  293. * Custom xstrlen()
  294. */
  295. static size_t
  296. xstrlen(const char *s)
  297. {
  298. static size_t len;
  299. if (!s)
  300. return 0;
  301. len = 0;
  302. while (*s)
  303. ++len, ++s;
  304. return len;
  305. }
  306. /*
  307. * Just a safe strncpy(3)
  308. * Always null ('\0') terminates if both src and dest are valid pointers.
  309. * Returns the number of bytes copied including terminating null byte.
  310. */
  311. static size_t
  312. xstrlcpy(char *dest, const char *src, size_t n)
  313. {
  314. static size_t len, blocks;
  315. static const uint lsize = sizeof(ulong);
  316. static const uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
  317. if (!src || !dest)
  318. return 0;
  319. len = xstrlen(src) + 1;
  320. if (n > len)
  321. n = len;
  322. else if (len > n)
  323. /* Save total number of bytes to copy in len */
  324. len = n;
  325. if (n >= lsize) {
  326. blocks = n >> _WSHIFT;
  327. n -= (blocks << _WSHIFT);
  328. } else
  329. blocks = 0;
  330. if (blocks) {
  331. static ulong *s, *d;
  332. s = (ulong *)src;
  333. d = (ulong *)dest;
  334. while (blocks) {
  335. *d = *s;
  336. ++d, ++s;
  337. --blocks;
  338. }
  339. if (!n) {
  340. dest = (char *)d;
  341. *--dest = '\0';
  342. return len;
  343. }
  344. src = (char *)s;
  345. dest = (char *)d;
  346. }
  347. while (--n && (*dest = *src))
  348. ++dest, ++src;
  349. if (!n)
  350. *dest = '\0';
  351. return len;
  352. }
  353. /*
  354. * Custom strcmp(), just what we need.
  355. * Returns 0 if same, -ve if s1 < s2, +ve if s1 > s2.
  356. */
  357. static int
  358. xstrcmp(const char *s1, const char *s2)
  359. {
  360. if (!s1 || !s2)
  361. return -1;
  362. while (*s1 && *s1 == *s2)
  363. ++s1, ++s2;
  364. return *s1 - *s2;
  365. }
  366. /*
  367. * The poor man's implementation of memrchr(3).
  368. * We are only looking for '/' in this program.
  369. * And we are NOT expecting a '/' at the end.
  370. * Ideally 0 < n <= strlen(s).
  371. */
  372. static void *
  373. xmemrchr(uchar *s, uchar ch, size_t n)
  374. {
  375. if (!s || !n)
  376. return NULL;
  377. s = s + n - 1;
  378. while (n) {
  379. if (*s == ch)
  380. return s;
  381. --n, --s;
  382. }
  383. return NULL;
  384. }
  385. /*
  386. * The following dirname(3) implementation does not
  387. * modify the input. We use a copy of the original.
  388. *
  389. * Modified from the glibc (GNU LGPL) version.
  390. */
  391. static char *
  392. xdirname(const char *path)
  393. {
  394. static char * const buf = g_buf, *last_slash, *runp;
  395. xstrlcpy(buf, path, PATH_MAX);
  396. /* Find last '/'. */
  397. last_slash = xmemrchr((uchar *)buf, '/', xstrlen(buf));
  398. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  399. /* Determine whether all remaining characters are slashes. */
  400. for (runp = last_slash; runp != buf; --runp)
  401. if (runp[-1] != '/')
  402. break;
  403. /* The '/' is the last character, we have to look further. */
  404. if (runp != buf)
  405. last_slash = xmemrchr((uchar *)buf, '/', runp - buf);
  406. }
  407. if (last_slash != NULL) {
  408. /* Determine whether all remaining characters are slashes. */
  409. for (runp = last_slash; runp != buf; --runp)
  410. if (runp[-1] != '/')
  411. break;
  412. /* Terminate the buffer. */
  413. if (runp == buf) {
  414. /* The last slash is the first character in the string.
  415. * We have to return "/". As a special case we have to
  416. * return "//" if there are exactly two slashes at the
  417. * beginning of the string. See XBD 4.10 Path Name
  418. * Resolution for more information.
  419. */
  420. if (last_slash == buf + 1)
  421. ++last_slash;
  422. else
  423. last_slash = buf + 1;
  424. } else
  425. last_slash = runp;
  426. last_slash[0] = '\0';
  427. } else {
  428. /* This assignment is ill-designed but the XPG specs require to
  429. * return a string containing "." in any case no directory part
  430. * is found and so a static and constant string is required.
  431. */
  432. buf[0] = '.';
  433. buf[1] = '\0';
  434. }
  435. return buf;
  436. }
  437. static char *
  438. xbasename(char *path)
  439. {
  440. static char *base;
  441. base = xmemrchr((uchar *)path, '/', xstrlen(path));
  442. return base ? base + 1 : path;
  443. }
  444. /*
  445. * Return number of dots if all chars in a string are dots, else 0
  446. */
  447. static int
  448. all_dots(const char *path)
  449. {
  450. int count = 0;
  451. if (!path)
  452. return FALSE;
  453. while (*path == '.')
  454. ++count, ++path;
  455. if (*path)
  456. return 0;
  457. return count;
  458. }
  459. /* Initialize curses mode */
  460. static void
  461. initcurses(void)
  462. {
  463. if (initscr() == NULL) {
  464. char *term = getenv("TERM");
  465. if (term != NULL)
  466. fprintf(stderr, "error opening TERM: %s\n", term);
  467. else
  468. fprintf(stderr, "initscr() failed\n");
  469. exit(1);
  470. }
  471. cbreak();
  472. noecho();
  473. nonl();
  474. intrflush(stdscr, FALSE);
  475. keypad(stdscr, TRUE);
  476. curs_set(FALSE); /* Hide cursor */
  477. start_color();
  478. use_default_colors();
  479. if (cfg.showcolor)
  480. init_pair(1, cfg.color, -1);
  481. settimeout(); /* One second */
  482. }
  483. /*
  484. * Spawns a child process. Behaviour can be controlled using flag.
  485. * Limited to 2 arguments to a program, flag works on bit set.
  486. */
  487. static void
  488. spawn(const char *file, const char *arg1, const char *arg2, const char *dir, uchar flag)
  489. {
  490. static char *shlvl;
  491. static pid_t pid;
  492. static int status;
  493. if (flag & F_NORMAL)
  494. exitcurses();
  495. pid = fork();
  496. if (pid == 0) {
  497. if (dir != NULL)
  498. status = chdir(dir);
  499. shlvl = getenv("SHLVL");
  500. /* Show a marker (to indicate nnn spawned shell) */
  501. if (flag & F_MARKER && shlvl != NULL) {
  502. printf("\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  503. printf("Spawned shell level: %d\n", atoi(shlvl) + 1);
  504. }
  505. /* Suppress stdout and stderr */
  506. if (flag & F_NOTRACE) {
  507. int fd = open("/dev/null", O_WRONLY, 0200);
  508. dup2(fd, 1);
  509. dup2(fd, 2);
  510. close(fd);
  511. }
  512. if (flag & F_SIGINT)
  513. signal(SIGINT, SIG_DFL);
  514. execlp(file, file, arg1, arg2, NULL);
  515. _exit(1);
  516. } else {
  517. if (!(flag & F_NOWAIT))
  518. /* Ignore interruptions */
  519. while (waitpid(pid, &status, 0) == -1)
  520. DPRINTF_D(status);
  521. DPRINTF_D(pid);
  522. if (flag & F_NORMAL)
  523. initcurses();
  524. }
  525. }
  526. /* Get program name from env var, else return fallback program */
  527. static char *
  528. xgetenv(const char *name, char *fallback)
  529. {
  530. static char *value;
  531. if (name == NULL)
  532. return fallback;
  533. value = getenv(name);
  534. return value && value[0] ? value : fallback;
  535. }
  536. /* Check if a dir exists, IS a dir and is readable */
  537. static bool
  538. xdiraccess(const char *path)
  539. {
  540. static DIR *dirp;
  541. dirp = opendir(path);
  542. if (dirp == NULL) {
  543. printwarn();
  544. return FALSE;
  545. }
  546. closedir(dirp);
  547. return TRUE;
  548. }
  549. /*
  550. * We assume none of the strings are NULL.
  551. *
  552. * Let's have the logic to sort numeric names in numeric order.
  553. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  554. *
  555. * If the absolute numeric values are same, we fallback to alphasort.
  556. */
  557. static int
  558. xstricmp(const char * const s1, const char * const s2)
  559. {
  560. static const char *c1, *c2;
  561. c1 = s1;
  562. while (isspace(*c1))
  563. ++c1;
  564. c2 = s2;
  565. while (isspace(*c2))
  566. ++c2;
  567. if (*c1 == '-' || *c1 == '+')
  568. ++c1;
  569. if (*c2 == '-' || *c2 == '+')
  570. ++c2;
  571. if (isdigit(*c1) && isdigit(*c2)) {
  572. while (*c1 >= '0' && *c1 <= '9')
  573. ++c1;
  574. while (isspace(*c1))
  575. ++c1;
  576. while (*c2 >= '0' && *c2 <= '9')
  577. ++c2;
  578. while (isspace(*c2))
  579. ++c2;
  580. }
  581. if (!*c1 && !*c2) {
  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. }
  592. return strcoll(s1, s2);
  593. }
  594. /* Return the integer value of a char representing HEX */
  595. static char
  596. xchartohex(char c)
  597. {
  598. if (c >= '0' && c <= '9')
  599. return c - '0';
  600. c = TOUPPER(c);
  601. if (c >= 'A' && c <= 'F')
  602. return c - 'A' + 10;
  603. return c;
  604. }
  605. /* Trim all whitespace from both ends, / from end */
  606. static char *
  607. strstrip(char *s)
  608. {
  609. if (!s || !*s)
  610. return s;
  611. size_t len = xstrlen(s) - 1;
  612. while (len != 0 && (isspace(s[len]) || s[len] == '/'))
  613. --len;
  614. s[len + 1] = '\0';
  615. while (*s && isspace(*s))
  616. ++s;
  617. return s;
  618. }
  619. static char *
  620. getmime(const char *file)
  621. {
  622. static regex_t regex;
  623. static uint i;
  624. static const uint len = LEN(assocs);
  625. for (i = 0; i < len; ++i) {
  626. if (regcomp(&regex, assocs[i].regex, REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  627. continue;
  628. if (regexec(&regex, file, 0, NULL, 0) == 0)
  629. return assocs[i].mime;
  630. }
  631. return NULL;
  632. }
  633. static int
  634. setfilter(regex_t *regex, char *filter)
  635. {
  636. static size_t len;
  637. static int r;
  638. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  639. if (r != 0 && filter && filter[0] != '\0') {
  640. len = COLS;
  641. if (len > NAME_MAX)
  642. len = NAME_MAX;
  643. regerror(r, regex, g_buf, len);
  644. printmsg(g_buf);
  645. }
  646. return r;
  647. }
  648. static void
  649. initfilter(int dot, char **ifilter)
  650. {
  651. *ifilter = dot ? "." : "^[^.]";
  652. }
  653. static int
  654. visible(regex_t *regex, char *file)
  655. {
  656. return regexec(regex, file, 0, NULL, 0) == 0;
  657. }
  658. static int
  659. entrycmp(const void *va, const void *vb)
  660. {
  661. static pEntry pa, pb;
  662. pa = (pEntry)va;
  663. pb = (pEntry)vb;
  664. /* Sort directories first */
  665. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  666. return 1;
  667. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  668. return -1;
  669. /* Do the actual sorting */
  670. if (cfg.mtimeorder)
  671. return pb->t - pa->t;
  672. if (cfg.sizeorder) {
  673. if (pb->size > pa->size)
  674. return 1;
  675. else if (pb->size < pa->size)
  676. return -1;
  677. }
  678. if (cfg.blkorder) {
  679. if (pb->blocks > pa->blocks)
  680. return 1;
  681. else if (pb->blocks < pa->blocks)
  682. return -1;
  683. }
  684. return xstricmp(pa->name, pb->name);
  685. }
  686. /*
  687. * Returns SEL_* if key is bound and 0 otherwise.
  688. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  689. * The next keyboard input can be simulated by presel.
  690. */
  691. static int
  692. nextsel(char **run, char **env, int *presel)
  693. {
  694. static int c;
  695. static uint i;
  696. static const uint len = LEN(bindings);
  697. #ifdef LINUX_INOTIFY
  698. static char inotify_buf[EVENT_BUF_LEN];
  699. #elif defined(BSD_KQUEUE)
  700. static struct kevent event_data[NUM_EVENT_SLOTS];
  701. #endif
  702. c = *presel;
  703. if (c == 0)
  704. c = getch();
  705. else {
  706. *presel = 0;
  707. /* Unwatch dir if we are still in a filtered view */
  708. #ifdef LINUX_INOTIFY
  709. if (inotify_wd >= 0) {
  710. inotify_rm_watch(inotify_fd, inotify_wd);
  711. inotify_wd = -1;
  712. }
  713. #elif defined(BSD_KQUEUE)
  714. if (event_fd >= 0) {
  715. close(event_fd);
  716. event_fd = -1;
  717. }
  718. #endif
  719. }
  720. if (c == -1) {
  721. ++idle;
  722. /* Do not check for directory changes in du
  723. * mode. A redraw forces du calculation.
  724. * Check for changes every odd second.
  725. */
  726. #ifdef LINUX_INOTIFY
  727. if (!cfg.blkorder && inotify_wd >= 0 && idle & 1 && read(inotify_fd, inotify_buf, EVENT_BUF_LEN) > 0)
  728. #elif defined(BSD_KQUEUE)
  729. if (!cfg.blkorder && event_fd >= 0 && idle & 1
  730. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS, event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  731. #endif
  732. c = CONTROL('L');
  733. } else
  734. idle = 0;
  735. for (i = 0; i < len; ++i)
  736. if (c == bindings[i].sym) {
  737. *run = bindings[i].run;
  738. *env = bindings[i].env;
  739. return bindings[i].act;
  740. }
  741. return 0;
  742. }
  743. /*
  744. * Move non-matching entries to the end
  745. */
  746. static void
  747. fill(struct entry **dents, int (*filter)(regex_t *, char *), regex_t *re)
  748. {
  749. static int count;
  750. static struct entry _dent, *dentp1, *dentp2;
  751. for (count = 0; count < ndents; ++count) {
  752. if (filter(re, (*dents)[count].name) == 0) {
  753. if (count != --ndents) {
  754. dentp1 = &(*dents)[count];
  755. dentp2 = &(*dents)[ndents];
  756. memcpy(&_dent, dentp1, sizeof(struct entry));
  757. memcpy(dentp1, dentp2, sizeof(struct entry));
  758. memcpy(dentp2, &_dent, sizeof(struct entry));
  759. --count;
  760. }
  761. continue;
  762. }
  763. }
  764. }
  765. static int
  766. matches(char *fltr)
  767. {
  768. static regex_t re;
  769. /* Search filter */
  770. if (setfilter(&re, fltr) != 0)
  771. return -1;
  772. fill(&dents, visible, &re);
  773. qsort(dents, ndents, sizeof(*dents), entrycmp);
  774. return 0;
  775. }
  776. static int
  777. filterentries(char *path)
  778. {
  779. static char ln[REGEX_MAX];
  780. static wchar_t wln[REGEX_MAX];
  781. static wint_t ch[2] = {0};
  782. int r, total = ndents, oldcur = cur, len = 1;
  783. char *pln = ln + 1;
  784. ln[0] = wln[0] = FILTER;
  785. ln[1] = wln[1] = '\0';
  786. cur = 0;
  787. cleartimeout();
  788. echo();
  789. curs_set(TRUE);
  790. printprompt(ln);
  791. while ((r = get_wch(ch)) != ERR) {
  792. if (*ch == 127 /* handle DEL */ || *ch == KEY_DC || *ch == KEY_BACKSPACE) {
  793. if (len == 1) {
  794. cur = oldcur;
  795. *ch = CONTROL('L');
  796. goto end;
  797. }
  798. wln[--len] = '\0';
  799. if (len == 1)
  800. cur = oldcur;
  801. wcstombs(ln, wln, REGEX_MAX);
  802. ndents = total;
  803. if (matches(pln) == -1)
  804. continue;
  805. redraw(path);
  806. printprompt(ln);
  807. continue;
  808. }
  809. if (r == OK) {
  810. switch (*ch) {
  811. case '\r': // with nonl(), this is ENTER key value
  812. if (len == 1) {
  813. cur = oldcur;
  814. goto end;
  815. }
  816. if (matches(pln) == -1)
  817. goto end;
  818. redraw(path);
  819. goto end;
  820. case CONTROL('L'):
  821. if (len == 1)
  822. cur = oldcur; // fallthrough
  823. case CONTROL('Q'):
  824. goto end;
  825. default:
  826. /* Reset cur in case it's a repeat search */
  827. if (len == 1)
  828. cur = 0;
  829. if (len == REGEX_MAX - 1)
  830. break;
  831. wln[len] = (wchar_t)*ch;
  832. wln[++len] = '\0';
  833. wcstombs(ln, wln, REGEX_MAX);
  834. ndents = total;
  835. if (matches(pln) == -1)
  836. continue;
  837. redraw(path);
  838. printprompt(ln);
  839. }
  840. } else {
  841. if (len == 1)
  842. cur = oldcur;
  843. goto end;
  844. }
  845. }
  846. end:
  847. noecho();
  848. curs_set(FALSE);
  849. settimeout();
  850. /* Return keys for navigation etc. */
  851. return *ch;
  852. }
  853. /* Show a prompt with input string and return the changes */
  854. static char *
  855. xreadline(char *fname)
  856. {
  857. int old_curs = curs_set(1);
  858. size_t len, pos;
  859. int x, y, r;
  860. wint_t ch[2] = {0};
  861. wchar_t *buf = (wchar_t *)g_buf;
  862. size_t buflen = NAME_MAX - 1;
  863. if (fname) {
  864. DPRINTF_S(fname);
  865. len = pos = mbstowcs(buf, fname, NAME_MAX);
  866. } else
  867. len = (size_t)-1;
  868. if (len == (size_t)-1) {
  869. buf[0] = '\0';
  870. len = pos = 0;
  871. }
  872. getyx(stdscr, y, x);
  873. cleartimeout();
  874. while (1) {
  875. buf[len] = ' ';
  876. mvaddnwstr(y, x, buf, len + 1);
  877. move(y, x + wcswidth(buf, pos));
  878. if ((r = get_wch(ch)) != ERR) {
  879. if (r == OK) {
  880. if (*ch == KEY_ENTER || *ch == '\n' || *ch == '\r')
  881. break;
  882. if (*ch == CONTROL('L')) {
  883. clearprompt();
  884. len = pos = 0;
  885. continue;
  886. }
  887. /* TAB breaks cursor position, ignore it */
  888. if (*ch == TAB || *ch == '\t')
  889. continue;
  890. if (pos < buflen) {
  891. memmove(buf + pos + 1, buf + pos, (len - pos) << 2);
  892. buf[pos] = *ch;
  893. ++len, ++pos;
  894. continue;
  895. }
  896. } else {
  897. switch (*ch) {
  898. case KEY_LEFT:
  899. if (pos > 0)
  900. --pos;
  901. break;
  902. case KEY_RIGHT:
  903. if (pos < len)
  904. ++pos;
  905. break;
  906. case KEY_BACKSPACE:
  907. if (pos > 0) {
  908. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  909. --len, --pos;
  910. }
  911. break;
  912. case KEY_DC:
  913. if (pos < len) {
  914. memmove(buf + pos, buf + pos + 1, (len - pos - 1) << 2);
  915. --len;
  916. }
  917. break;
  918. default:
  919. break;
  920. }
  921. }
  922. }
  923. }
  924. buf[len] = '\0';
  925. if (old_curs != ERR) curs_set(old_curs);
  926. settimeout();
  927. DPRINTF_S(buf);
  928. wcstombs(g_buf, buf, NAME_MAX);
  929. return g_buf;
  930. }
  931. static char *
  932. readinput(void)
  933. {
  934. cleartimeout();
  935. echo();
  936. curs_set(TRUE);
  937. memset(g_buf, 0, NAME_MAX + 1);
  938. wgetnstr(stdscr, g_buf, NAME_MAX);
  939. noecho();
  940. curs_set(FALSE);
  941. settimeout();
  942. return g_buf[0] ? g_buf : NULL;
  943. }
  944. /*
  945. * Returns "dir/name or "/name"
  946. */
  947. static char *
  948. mkpath(char *dir, char *name, char *out, size_t n)
  949. {
  950. /* Handle absolute path */
  951. if (name[0] == '/')
  952. xstrlcpy(out, name, n);
  953. else {
  954. /* Handle root case */
  955. if (istopdir(dir))
  956. snprintf(out, n, "/%s", name);
  957. else
  958. snprintf(out, n, "%s/%s", dir, name);
  959. }
  960. return out;
  961. }
  962. static void
  963. parsebmstr(char *bms)
  964. {
  965. int i = 0;
  966. while (*bms && i < BM_MAX) {
  967. bookmark[i].key = bms;
  968. ++bms;
  969. while (*bms && *bms != ':')
  970. ++bms;
  971. if (!*bms) {
  972. bookmark[i].key = NULL;
  973. break;
  974. }
  975. *bms = '\0';
  976. bookmark[i].loc = ++bms;
  977. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  978. bookmark[i].key = NULL;
  979. break;
  980. }
  981. while (*bms && *bms != ';')
  982. ++bms;
  983. if (*bms)
  984. *bms = '\0';
  985. else
  986. break;
  987. ++bms;
  988. ++i;
  989. }
  990. }
  991. /*
  992. * Get the real path to a bookmark
  993. *
  994. * NULL is returned in case of no match, path resolution failure etc.
  995. * buf would be modified, so check return value before access
  996. */
  997. static char *
  998. get_bm_loc(char *key, char *buf)
  999. {
  1000. if (!key || !key[0])
  1001. return NULL;
  1002. for (int r = 0; bookmark[r].key && r < BM_MAX; ++r) {
  1003. if (xstrcmp(bookmark[r].key, key) == 0) {
  1004. if (bookmark[r].loc[0] == '~') {
  1005. char *home = getenv("HOME");
  1006. if (!home) {
  1007. DPRINTF_S(STR_NOHOME);
  1008. return NULL;
  1009. }
  1010. snprintf(buf, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  1011. } else
  1012. xstrlcpy(buf, bookmark[r].loc, PATH_MAX);
  1013. return buf;
  1014. }
  1015. }
  1016. DPRINTF_S("Invalid key");
  1017. return NULL;
  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(const 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(const 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 | First entry\n"
  1437. "2End, G, $, ^E | 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 entry\n"
  1457. "es | Toggle sort by size\n"
  1458. "eS | Toggle du 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 cd\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, const char *fname, int n)
  1660. {
  1661. static int i;
  1662. if (!fname)
  1663. return 0;
  1664. DPRINTF_S(fname);
  1665. for (i = 0; i < n; ++i)
  1666. if (xstrcmp(fname, dents[i].name) == 0)
  1667. return i;
  1668. return 0;
  1669. }
  1670. static int
  1671. populate(char *path, char *oldname, char *fltr)
  1672. {
  1673. static regex_t re;
  1674. /* Can fail when permissions change while browsing.
  1675. * It's assumed that path IS a directory when we are here.
  1676. */
  1677. if (access(path, R_OK) == -1)
  1678. return -1;
  1679. /* Search filter */
  1680. if (setfilter(&re, fltr) != 0)
  1681. return -1;
  1682. if (cfg.blkorder) {
  1683. printmsg("Calculating...");
  1684. refresh();
  1685. }
  1686. #ifdef DEBUGMODE
  1687. struct timespec ts1, ts2;
  1688. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  1689. #endif
  1690. ndents = dentfill(path, &dents, visible, &re);
  1691. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1692. #ifdef DEBUGMODE
  1693. clock_gettime(CLOCK_REALTIME, &ts2);
  1694. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  1695. #endif
  1696. /* Find cur from history */
  1697. cur = dentfind(dents, oldname, ndents);
  1698. return 0;
  1699. }
  1700. static void
  1701. redraw(char *path)
  1702. {
  1703. static char buf[(NAME_MAX + 1) << 1];
  1704. static size_t ncols;
  1705. static int nlines, i;
  1706. static bool mode_changed;
  1707. mode_changed = FALSE;
  1708. nlines = MIN(LINES - 4, ndents);
  1709. /* Clean screen */
  1710. erase();
  1711. /* Fail redraw if < than 10 columns */
  1712. if (COLS < 10) {
  1713. printmsg("Too few columns!");
  1714. return;
  1715. }
  1716. /* Strip trailing slashes */
  1717. for (i = xstrlen(path) - 1; i > 0; --i)
  1718. if (path[i] == '/')
  1719. path[i] = '\0';
  1720. else
  1721. break;
  1722. DPRINTF_D(cur);
  1723. DPRINTF_S(path);
  1724. if (!realpath(path, g_buf)) {
  1725. printwarn();
  1726. return;
  1727. }
  1728. ncols = COLS;
  1729. if (ncols > PATH_MAX)
  1730. ncols = PATH_MAX;
  1731. /* No text wrapping in cwd line */
  1732. /* Show CWD: - xstrlen(CWD) - 1 = 6 */
  1733. g_buf[ncols - 6] = '\0';
  1734. printw(CWD "%s\n\n", g_buf);
  1735. /* Fallback to light mode if less than 35 columns */
  1736. if (ncols < 35 && cfg.showdetail) {
  1737. cfg.showdetail ^= 1;
  1738. printptr = &printent;
  1739. mode_changed = TRUE;
  1740. }
  1741. /* Calculate the number of cols available to print entry name */
  1742. if (cfg.showdetail)
  1743. ncols -= 32;
  1744. else
  1745. ncols -= 5;
  1746. if (cfg.showcolor) {
  1747. attron(COLOR_PAIR(1) | A_BOLD);
  1748. cfg.dircolor = 1;
  1749. }
  1750. /* Print listing */
  1751. if (cur < (nlines >> 1)) {
  1752. for (i = 0; i < nlines; ++i)
  1753. printptr(&dents[i], i == cur, ncols);
  1754. } else if (cur >= ndents - (nlines >> 1)) {
  1755. for (i = ndents - nlines; i < ndents; ++i)
  1756. printptr(&dents[i], i == cur, ncols);
  1757. } else {
  1758. static int odd;
  1759. odd = ISODD(nlines);
  1760. nlines >>= 1;
  1761. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1762. printptr(&dents[i], i == cur, ncols);
  1763. }
  1764. /* Must reset e.g. no files in dir */
  1765. if (cfg.dircolor) {
  1766. attroff(COLOR_PAIR(1) | A_BOLD);
  1767. cfg.dircolor = 0;
  1768. }
  1769. if (cfg.showdetail) {
  1770. if (ndents) {
  1771. static char ind[2] = "\0\0";
  1772. static char sort[9];
  1773. if (cfg.mtimeorder)
  1774. sprintf(sort, "by time ");
  1775. else if (cfg.sizeorder)
  1776. sprintf(sort, "by size ");
  1777. else
  1778. sort[0] = '\0';
  1779. if (S_ISDIR(dents[cur].mode))
  1780. ind[0] = '/';
  1781. else if (S_ISLNK(dents[cur].mode))
  1782. ind[0] = '@';
  1783. else if (S_ISSOCK(dents[cur].mode))
  1784. ind[0] = '=';
  1785. else if (S_ISFIFO(dents[cur].mode))
  1786. ind[0] = '|';
  1787. else if (dents[cur].mode & 0100)
  1788. ind[0] = '*';
  1789. else
  1790. ind[0] = '\0';
  1791. /* We need to show filename as it may be truncated in directory listing */
  1792. if (!cfg.blkorder)
  1793. sprintf(buf, "%d/%d %s[%s%s]", cur + 1, ndents, sort, unescape(dents[cur].name, 0), ind);
  1794. else {
  1795. i = sprintf(buf, "%d/%d du: %s (%lu files) ", cur + 1, ndents, coolsize(dir_blocks << 9), num_files);
  1796. sprintf(buf + i, "vol: %s free [%s%s]", coolsize(get_fs_free(path)), unescape(dents[cur].name, 0), ind);
  1797. }
  1798. printmsg(buf);
  1799. } else
  1800. printmsg("0 items");
  1801. }
  1802. if (mode_changed) {
  1803. cfg.showdetail ^= 1;
  1804. printptr = &printent_long;
  1805. }
  1806. }
  1807. static void
  1808. browse(char *ipath, char *ifilter)
  1809. {
  1810. static char path[PATH_MAX], newpath[PATH_MAX], lastdir[PATH_MAX], mark[PATH_MAX];
  1811. static char fltr[NAME_MAX + 1];
  1812. static char oldname[NAME_MAX + 1];
  1813. char *dir, *tmp, *run = NULL, *env = NULL;
  1814. struct stat sb;
  1815. int r, fd, presel;
  1816. enum action sel = SEL_RUNARG + 1;
  1817. bool dir_changed = FALSE;
  1818. xstrlcpy(path, ipath, PATH_MAX);
  1819. copyfilter();
  1820. oldname[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  1821. if (cfg.filtermode)
  1822. presel = FILTER;
  1823. else
  1824. presel = 0;
  1825. /* Allocate buffer to hold names */
  1826. pnamebuf = (char *)malloc(NAMEBUF_INCR);
  1827. if (pnamebuf == NULL)
  1828. errexit();
  1829. begin:
  1830. #ifdef LINUX_INOTIFY
  1831. if (dir_changed && inotify_wd >= 0) {
  1832. inotify_rm_watch(inotify_fd, inotify_wd);
  1833. inotify_wd = -1;
  1834. dir_changed = FALSE;
  1835. }
  1836. #elif defined(BSD_KQUEUE)
  1837. if (dir_changed && event_fd >= 0) {
  1838. close(event_fd);
  1839. event_fd = -1;
  1840. dir_changed = FALSE;
  1841. }
  1842. #endif
  1843. if (populate(path, oldname, fltr) == -1) {
  1844. printwarn();
  1845. goto nochange;
  1846. }
  1847. #ifdef LINUX_INOTIFY
  1848. if (inotify_wd == -1)
  1849. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  1850. #elif defined(BSD_KQUEUE)
  1851. if (event_fd == -1) {
  1852. #if defined(O_EVTONLY)
  1853. event_fd = open(path, O_EVTONLY);
  1854. #else
  1855. event_fd = open(path, O_RDONLY);
  1856. #endif
  1857. if (event_fd >= 0)
  1858. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  1859. }
  1860. #endif
  1861. for (;;) {
  1862. redraw(path);
  1863. nochange:
  1864. /* Exit if parent has exited */
  1865. if (getppid() == 1)
  1866. _exit(0);
  1867. sel = nextsel(&run, &env, &presel);
  1868. switch (sel) {
  1869. case SEL_BACK:
  1870. /* There is no going back */
  1871. if (istopdir(path)) {
  1872. printmsg(STR_ATROOT);
  1873. goto nochange;
  1874. }
  1875. dir = xdirname(path);
  1876. if (access(dir, R_OK) == -1) {
  1877. printwarn();
  1878. goto nochange;
  1879. }
  1880. /* Save history */
  1881. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  1882. /* Save last working directory */
  1883. xstrlcpy(lastdir, path, PATH_MAX);
  1884. dir_changed = TRUE;
  1885. xstrlcpy(path, dir, PATH_MAX);
  1886. /* Reset filter */
  1887. copyfilter();
  1888. if (cfg.filtermode)
  1889. presel = FILTER;
  1890. goto begin;
  1891. case SEL_GOIN:
  1892. /* Cannot descend in empty directories */
  1893. if (ndents == 0)
  1894. goto begin;
  1895. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1896. DPRINTF_S(newpath);
  1897. /* Get path info */
  1898. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1899. if (fd == -1) {
  1900. printwarn();
  1901. goto nochange;
  1902. }
  1903. if (fstat(fd, &sb) == -1) {
  1904. printwarn();
  1905. close(fd);
  1906. goto nochange;
  1907. }
  1908. close(fd);
  1909. DPRINTF_U(sb.st_mode);
  1910. switch (sb.st_mode & S_IFMT) {
  1911. case S_IFDIR:
  1912. if (access(newpath, R_OK) == -1) {
  1913. printwarn();
  1914. goto nochange;
  1915. }
  1916. /* Save last working directory */
  1917. xstrlcpy(lastdir, path, PATH_MAX);
  1918. dir_changed = TRUE;
  1919. xstrlcpy(path, newpath, PATH_MAX);
  1920. oldname[0] = '\0';
  1921. /* Reset filter */
  1922. copyfilter();
  1923. if (cfg.filtermode)
  1924. presel = FILTER;
  1925. goto begin;
  1926. case S_IFREG:
  1927. {
  1928. /* If NNN_USE_EDITOR is set,
  1929. * open text in EDITOR
  1930. */
  1931. if (editor) {
  1932. if (getmime(dents[cur].name)) {
  1933. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1934. continue;
  1935. }
  1936. /* Recognize and open plain
  1937. * text files with vi
  1938. */
  1939. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  1940. continue;
  1941. if (strstr(g_buf, "text/") == g_buf) {
  1942. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1943. continue;
  1944. }
  1945. }
  1946. /* Invoke desktop opener as last resort */
  1947. spawn(utils[2], newpath, NULL, NULL, nowait);
  1948. continue;
  1949. }
  1950. default:
  1951. printmsg("Unsupported file");
  1952. goto nochange;
  1953. }
  1954. case SEL_NEXT:
  1955. if (cur < ndents - 1)
  1956. ++cur;
  1957. else if (ndents)
  1958. /* Roll over, set cursor to first entry */
  1959. cur = 0;
  1960. break;
  1961. case SEL_PREV:
  1962. if (cur > 0)
  1963. --cur;
  1964. else if (ndents)
  1965. /* Roll over, set cursor to last entry */
  1966. cur = ndents - 1;
  1967. break;
  1968. case SEL_PGDN:
  1969. if (cur < ndents - 1)
  1970. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1971. break;
  1972. case SEL_PGUP:
  1973. if (cur > 0)
  1974. cur -= MIN((LINES - 4) / 2, cur);
  1975. break;
  1976. case SEL_HOME:
  1977. cur = 0;
  1978. break;
  1979. case SEL_END:
  1980. cur = ndents - 1;
  1981. break;
  1982. case SEL_CD:
  1983. {
  1984. char *input;
  1985. int truecd;
  1986. /* Save the program start dir */
  1987. tmp = getcwd(newpath, PATH_MAX);
  1988. if (tmp == NULL) {
  1989. printwarn();
  1990. goto nochange;
  1991. }
  1992. /* Switch to current path for readline(3) */
  1993. if (chdir(path) == -1) {
  1994. printwarn();
  1995. goto nochange;
  1996. }
  1997. exitcurses();
  1998. tmp = readline("chdir: ");
  1999. initcurses();
  2000. /* Change back to program start dir */
  2001. if (chdir(newpath) == -1)
  2002. printwarn();
  2003. if (tmp[0] == '\0')
  2004. break;
  2005. /* Add to readline(3) history */
  2006. add_history(tmp);
  2007. input = tmp;
  2008. tmp = strstrip(tmp);
  2009. if (tmp[0] == '\0') {
  2010. free(input);
  2011. break;
  2012. }
  2013. truecd = 0;
  2014. if (tmp[0] == '~') {
  2015. /* Expand ~ to HOME absolute path */
  2016. char *home = getenv("HOME");
  2017. if (home)
  2018. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  2019. else {
  2020. free(input);
  2021. printmsg(STR_NOHOME);
  2022. goto nochange;
  2023. }
  2024. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  2025. if (lastdir[0] == '\0') {
  2026. free(input);
  2027. break;
  2028. }
  2029. /* Switch to last visited dir */
  2030. xstrlcpy(newpath, lastdir, PATH_MAX);
  2031. truecd = 1;
  2032. } else if ((r = all_dots(tmp))) {
  2033. if (r == 1) {
  2034. /* Always in the current dir */
  2035. free(input);
  2036. break;
  2037. }
  2038. /* Show a message if already at / */
  2039. if (istopdir(path)) {
  2040. printmsg(STR_ATROOT);
  2041. free(input);
  2042. goto nochange;
  2043. }
  2044. --r; /* One . for the current dir */
  2045. dir = path;
  2046. /* Note: fd is used as a tmp variable here */
  2047. for (fd = 0; fd < r; ++fd) {
  2048. /* Reached / ? */
  2049. if (istopdir(path)) {
  2050. /* Can't cd beyond / */
  2051. break;
  2052. }
  2053. dir = xdirname(dir);
  2054. if (access(dir, R_OK) == -1) {
  2055. printwarn();
  2056. free(input);
  2057. goto nochange;
  2058. }
  2059. }
  2060. truecd = 1;
  2061. /* Save the path in case of cd ..
  2062. * We mark the current dir in parent dir
  2063. */
  2064. if (r == 1) {
  2065. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2066. truecd = 2;
  2067. }
  2068. xstrlcpy(newpath, dir, PATH_MAX);
  2069. } else
  2070. mkpath(path, tmp, newpath, PATH_MAX);
  2071. free(input);
  2072. if (!xdiraccess(newpath))
  2073. goto nochange;
  2074. if (truecd == 0) {
  2075. /* Probable change in dir */
  2076. /* No-op if it's the same directory */
  2077. if (xstrcmp(path, newpath) == 0)
  2078. break;
  2079. oldname[0] = '\0';
  2080. } else if (truecd == 1)
  2081. /* Sure change in dir */
  2082. oldname[0] = '\0';
  2083. /* Save last working directory */
  2084. xstrlcpy(lastdir, path, PATH_MAX);
  2085. dir_changed = TRUE;
  2086. /* Save the newly opted dir in path */
  2087. xstrlcpy(path, newpath, PATH_MAX);
  2088. /* Reset filter */
  2089. copyfilter();
  2090. DPRINTF_S(path);
  2091. if (cfg.filtermode)
  2092. presel = FILTER;
  2093. goto begin;
  2094. }
  2095. case SEL_CDHOME:
  2096. dir = getenv("HOME");
  2097. if (dir == NULL) {
  2098. clearprompt();
  2099. goto nochange;
  2100. } // fallthrough
  2101. case SEL_CDBEGIN:
  2102. if (sel == SEL_CDBEGIN)
  2103. dir = ipath;
  2104. if (!xdiraccess(dir)) {
  2105. goto nochange;
  2106. }
  2107. if (xstrcmp(path, dir) == 0) {
  2108. break;
  2109. }
  2110. /* Save last working directory */
  2111. xstrlcpy(lastdir, path, PATH_MAX);
  2112. dir_changed = TRUE;
  2113. xstrlcpy(path, dir, PATH_MAX);
  2114. oldname[0] = '\0';
  2115. /* Reset filter */
  2116. copyfilter();
  2117. DPRINTF_S(path);
  2118. if (cfg.filtermode)
  2119. presel = FILTER;
  2120. goto begin;
  2121. case SEL_CDLAST: // fallthrough
  2122. case SEL_VISIT:
  2123. if (sel == SEL_VISIT) {
  2124. if (xstrcmp(mark, path) == 0)
  2125. break;
  2126. tmp = mark;
  2127. } else
  2128. tmp = lastdir;
  2129. if (tmp[0] == '\0') {
  2130. printmsg("Not set...");
  2131. goto nochange;
  2132. }
  2133. if (!xdiraccess(tmp))
  2134. goto nochange;
  2135. xstrlcpy(newpath, tmp, PATH_MAX);
  2136. xstrlcpy(lastdir, path, PATH_MAX);
  2137. dir_changed = TRUE;
  2138. xstrlcpy(path, newpath, PATH_MAX);
  2139. oldname[0] = '\0';
  2140. /* Reset filter */
  2141. copyfilter();
  2142. DPRINTF_S(path);
  2143. if (cfg.filtermode)
  2144. presel = FILTER;
  2145. goto begin;
  2146. case SEL_CDBM:
  2147. printprompt("key: ");
  2148. tmp = readinput();
  2149. clearprompt();
  2150. if (tmp == NULL)
  2151. break;
  2152. if (get_bm_loc(tmp, newpath) == NULL) {
  2153. printmsg(STR_INVBM);
  2154. goto nochange;
  2155. }
  2156. if (!xdiraccess(newpath))
  2157. goto nochange;
  2158. if (xstrcmp(path, newpath) == 0)
  2159. break;
  2160. oldname[0] = '\0';
  2161. /* Save last working directory */
  2162. xstrlcpy(lastdir, path, PATH_MAX);
  2163. dir_changed = TRUE;
  2164. /* Save the newly opted dir in path */
  2165. xstrlcpy(path, newpath, PATH_MAX);
  2166. /* Reset filter */
  2167. copyfilter();
  2168. DPRINTF_S(path);
  2169. if (cfg.filtermode)
  2170. presel = FILTER;
  2171. goto begin;
  2172. case SEL_PIN:
  2173. xstrlcpy(mark, path, PATH_MAX);
  2174. printmsg(mark);
  2175. goto nochange;
  2176. case SEL_FLTR:
  2177. presel = filterentries(path);
  2178. copyfilter();
  2179. DPRINTF_S(fltr);
  2180. /* Save current */
  2181. if (ndents > 0)
  2182. copycurname();
  2183. goto nochange;
  2184. case SEL_MFLTR:
  2185. cfg.filtermode ^= 1;
  2186. if (cfg.filtermode)
  2187. presel = FILTER;
  2188. else
  2189. printmsg("navigate-as-you-type off");
  2190. goto nochange;
  2191. case SEL_SEARCH:
  2192. spawn(player, path, "search", NULL, F_NORMAL);
  2193. break;
  2194. case SEL_TOGGLEDOT:
  2195. cfg.showhidden ^= 1;
  2196. initfilter(cfg.showhidden, &ifilter);
  2197. copyfilter();
  2198. goto begin;
  2199. case SEL_DETAIL:
  2200. cfg.showdetail ^= 1;
  2201. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2202. /* Save current */
  2203. if (ndents > 0)
  2204. copycurname();
  2205. goto begin;
  2206. case SEL_STATS:
  2207. if (ndents > 0) {
  2208. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2209. if (lstat(newpath, &sb) == -1) {
  2210. if (dents)
  2211. dentfree(dents);
  2212. errexit();
  2213. } else {
  2214. if (show_stats(newpath, dents[cur].name, &sb) < 0) {
  2215. printwarn();
  2216. goto nochange;
  2217. }
  2218. }
  2219. }
  2220. break;
  2221. case SEL_LIST: // fallthrough
  2222. case SEL_EXTRACT: // fallthrough
  2223. case SEL_MEDIA: // fallthrough
  2224. case SEL_FMEDIA:
  2225. if (ndents > 0) {
  2226. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2227. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2228. r = show_mediainfo(newpath, run);
  2229. else
  2230. r = handle_archive(newpath, run, path);
  2231. if (r == -1) {
  2232. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2233. sprintf(g_buf, "%s missing", utils[cfg.metaviewer]);
  2234. else
  2235. sprintf(g_buf, "%s missing", utils[4]);
  2236. printmsg(g_buf);
  2237. goto nochange;
  2238. }
  2239. }
  2240. break;
  2241. case SEL_DFB:
  2242. if (!desktop_manager) {
  2243. printmsg("NNN_DE_FILE_MANAGER not set");
  2244. goto nochange;
  2245. }
  2246. spawn(desktop_manager, path, NULL, path, F_NOTRACE | F_NOWAIT);
  2247. break;
  2248. case SEL_FSIZE:
  2249. cfg.sizeorder ^= 1;
  2250. cfg.mtimeorder = 0;
  2251. cfg.blkorder = 0;
  2252. /* Save current */
  2253. if (ndents > 0)
  2254. copycurname();
  2255. goto begin;
  2256. case SEL_BSIZE:
  2257. cfg.blkorder ^= 1;
  2258. if (cfg.blkorder) {
  2259. cfg.showdetail = 1;
  2260. printptr = &printent_long;
  2261. }
  2262. cfg.mtimeorder = 0;
  2263. cfg.sizeorder = 0;
  2264. /* Save current */
  2265. if (ndents > 0)
  2266. copycurname();
  2267. goto begin;
  2268. case SEL_MTIME:
  2269. cfg.mtimeorder ^= 1;
  2270. cfg.sizeorder = 0;
  2271. cfg.blkorder = 0;
  2272. /* Save current */
  2273. if (ndents > 0)
  2274. copycurname();
  2275. goto begin;
  2276. case SEL_REDRAW:
  2277. /* Save current */
  2278. if (ndents > 0)
  2279. copycurname();
  2280. goto begin;
  2281. case SEL_COPY:
  2282. if (copier && ndents) {
  2283. if (istopdir(path))
  2284. snprintf(newpath, PATH_MAX, "/%s", dents[cur].name);
  2285. else
  2286. snprintf(newpath, PATH_MAX, "%s/%s", path, dents[cur].name);
  2287. spawn(copier, newpath, NULL, NULL, F_NONE);
  2288. printmsg(newpath);
  2289. } else if (!copier)
  2290. printmsg("NNN_COPIER is not set");
  2291. goto nochange;
  2292. case SEL_NEW:
  2293. printprompt("name: ");
  2294. tmp = xreadline(NULL);
  2295. clearprompt();
  2296. if (tmp == NULL || tmp[0] == '\0')
  2297. break;
  2298. /* Allow only relative, same dir paths */
  2299. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  2300. printmsg(STR_INPUT);
  2301. goto nochange;
  2302. }
  2303. /* Open the descriptor to currently open directory */
  2304. fd = open(path, O_RDONLY | O_DIRECTORY);
  2305. if (fd == -1) {
  2306. printwarn();
  2307. goto nochange;
  2308. }
  2309. /* Check if another file with same name exists */
  2310. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2311. printmsg("Entry exists");
  2312. goto nochange;
  2313. }
  2314. /* Check if it's a dir or file */
  2315. printprompt("Press 'f' for file or 'd' for dir");
  2316. cleartimeout();
  2317. r = getch();
  2318. settimeout();
  2319. if (r == 'f') {
  2320. r = openat(fd, tmp, O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
  2321. close(r);
  2322. } else if (r == 'd')
  2323. r = mkdirat(fd, tmp, S_IRWXU | S_IRWXG | S_IRWXO);
  2324. else {
  2325. close(fd);
  2326. break;
  2327. }
  2328. if (r == -1) {
  2329. printwarn();
  2330. close(fd);
  2331. goto nochange;
  2332. }
  2333. close(fd);
  2334. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2335. goto begin;
  2336. case SEL_RENAME:
  2337. if (ndents <= 0)
  2338. break;
  2339. printprompt("");
  2340. tmp = xreadline(dents[cur].name);
  2341. clearprompt();
  2342. if (tmp == NULL || tmp[0] == '\0')
  2343. break;
  2344. /* Allow only relative, same dir paths */
  2345. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  2346. printmsg(STR_INPUT);
  2347. goto nochange;
  2348. }
  2349. /* Skip renaming to same name */
  2350. if (xstrcmp(tmp, dents[cur].name) == 0)
  2351. break;
  2352. /* Open the descriptor to currently open directory */
  2353. fd = open(path, O_RDONLY | O_DIRECTORY);
  2354. if (fd == -1) {
  2355. printwarn();
  2356. goto nochange;
  2357. }
  2358. /* Check if another file with same name exists */
  2359. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2360. /* File with the same name exists */
  2361. printprompt("Press 'y' to overwrite");
  2362. cleartimeout();
  2363. r = getch();
  2364. settimeout();
  2365. if (r != 'y') {
  2366. close(fd);
  2367. break;
  2368. }
  2369. }
  2370. /* Rename the file */
  2371. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  2372. printwarn();
  2373. close(fd);
  2374. goto nochange;
  2375. }
  2376. close(fd);
  2377. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2378. goto begin;
  2379. case SEL_HELP:
  2380. show_help(path);
  2381. break;
  2382. case SEL_RUN:
  2383. run = xgetenv(env, run);
  2384. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2385. /* Repopulate as directory content may have changed */
  2386. goto begin;
  2387. case SEL_RUNARG:
  2388. run = xgetenv(env, run);
  2389. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2390. break;
  2391. case SEL_CDQUIT:
  2392. {
  2393. char *tmpfile = "/tmp/nnn";
  2394. tmp = getenv("NNN_TMPFILE");
  2395. if (tmp)
  2396. tmpfile = tmp;
  2397. FILE *fp = fopen(tmpfile, "w");
  2398. if (fp) {
  2399. fprintf(fp, "cd \"%s\"", path);
  2400. fclose(fp);
  2401. }
  2402. /* Fall through to exit */
  2403. } // fallthrough
  2404. case SEL_QUIT:
  2405. dentfree(dents);
  2406. return;
  2407. }
  2408. /* Screensaver */
  2409. if (idletimeout != 0 && idle == idletimeout) {
  2410. idle = 0;
  2411. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2412. }
  2413. }
  2414. }
  2415. static void
  2416. usage(void)
  2417. {
  2418. printf("usage: nnn [-b key] [-c N] [-e] [-i] [-l]\n\
  2419. [-p nlay] [-S] [-v] [-h] [PATH]\n\n\
  2420. The missing terminal file browser for X.\n\n\
  2421. positional arguments:\n\
  2422. PATH start dir [default: current dir]\n\n\
  2423. optional arguments:\n\
  2424. -b key specify bookmark key to open\n\
  2425. -c N specify dir color, disables if N>7\n\
  2426. -e use exiftool instead of mediainfo\n\
  2427. -i start in navigate-as-you-type mode\n\
  2428. -l start in light mode (fewer details)\n\
  2429. -p nlay path to custom nlay\n\
  2430. -S start in disk usage analyzer mode\n\
  2431. -v show program version and exit\n\
  2432. -h show this help and exit\n\n\
  2433. Version: %s\n%s\n", VERSION, GENERAL_INFO);
  2434. exit(0);
  2435. }
  2436. int
  2437. main(int argc, char *argv[])
  2438. {
  2439. static char cwd[PATH_MAX];
  2440. char *ipath = NULL, *ifilter, *bmstr;
  2441. int opt;
  2442. /* Confirm we are in a terminal */
  2443. if (!isatty(0) || !isatty(1)) {
  2444. fprintf(stderr, "stdin or stdout is not a tty\n");
  2445. exit(1);
  2446. }
  2447. while ((opt = getopt(argc, argv, "Slib:c:ep:vh")) != -1) {
  2448. switch (opt) {
  2449. case 'S':
  2450. cfg.blkorder = 1;
  2451. break;
  2452. case 'l':
  2453. cfg.showdetail = 0;
  2454. printptr = &printent;
  2455. break;
  2456. case 'i':
  2457. cfg.filtermode = 1;
  2458. break;
  2459. case 'b':
  2460. ipath = optarg;
  2461. break;
  2462. case 'c':
  2463. if (atoi(optarg) > 7)
  2464. cfg.showcolor = 0;
  2465. else
  2466. cfg.color = (uchar)atoi(optarg);
  2467. break;
  2468. case 'e':
  2469. cfg.metaviewer = 1;
  2470. break;
  2471. case 'p':
  2472. player = optarg;
  2473. break;
  2474. case 'v':
  2475. printf("%s\n", VERSION);
  2476. return 0;
  2477. case 'h': // fallthrough
  2478. default:
  2479. usage();
  2480. }
  2481. }
  2482. /* Parse bookmarks string, if available */
  2483. bmstr = getenv("NNN_BMS");
  2484. if (bmstr)
  2485. parsebmstr(bmstr);
  2486. if (ipath) { /* Open a bookmark directly */
  2487. if (get_bm_loc(ipath, cwd) == NULL) {
  2488. fprintf(stderr, "%s\n", STR_INVBM);
  2489. exit(1);
  2490. }
  2491. ipath = cwd;
  2492. } else if (argc == optind) {
  2493. /* Start in the current directory */
  2494. ipath = getcwd(cwd, PATH_MAX);
  2495. if (ipath == NULL)
  2496. ipath = "/";
  2497. } else {
  2498. ipath = realpath(argv[optind], cwd);
  2499. if (!ipath) {
  2500. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2501. exit(1);
  2502. }
  2503. }
  2504. /* Increase current open file descriptor limit */
  2505. open_max = max_openfds();
  2506. if (getuid() == 0)
  2507. cfg.showhidden = 1;
  2508. initfilter(cfg.showhidden, &ifilter);
  2509. #ifdef LINUX_INOTIFY
  2510. /* Initialize inotify */
  2511. inotify_fd = inotify_init1(IN_NONBLOCK);
  2512. if (inotify_fd < 0) {
  2513. fprintf(stderr, "inotify init! %s\n", strerror(errno));
  2514. exit(1);
  2515. }
  2516. #elif defined(BSD_KQUEUE)
  2517. kq = kqueue();
  2518. if (kq < 0) {
  2519. fprintf(stderr, "kqueue init! %s\n", strerror(errno));
  2520. exit(1);
  2521. }
  2522. gtimeout.tv_sec = 0;
  2523. gtimeout.tv_nsec = 0;
  2524. #endif
  2525. /* Edit text in EDITOR, if opted */
  2526. if (getenv("NNN_USE_EDITOR"))
  2527. editor = xgetenv("EDITOR", "vi");
  2528. /* Set player if not set already */
  2529. if (!player)
  2530. player = utils[3];
  2531. /* Get the desktop file browser, if set */
  2532. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2533. /* Get screensaver wait time, if set; copier used as tmp var */
  2534. copier = getenv("NNN_IDLE_TIMEOUT");
  2535. if (copier)
  2536. idletimeout = abs(atoi(copier));
  2537. /* Get the default copier, if set */
  2538. copier = getenv("NNN_COPIER");
  2539. /* Get nowait flag */
  2540. nowait |= getenv("NNN_NOWAIT") ? F_NOWAIT : 0;
  2541. signal(SIGINT, SIG_IGN);
  2542. /* Test initial path */
  2543. if (!xdiraccess(ipath)) {
  2544. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2545. exit(1);
  2546. }
  2547. /* Set locale */
  2548. setlocale(LC_ALL, "");
  2549. #ifdef DEBUGMODE
  2550. enabledbg();
  2551. #endif
  2552. initcurses();
  2553. browse(ipath, ifilter);
  2554. exitcurses();
  2555. #ifdef LINUX_INOTIFY
  2556. /* Shutdown inotify */
  2557. if (inotify_wd >= 0)
  2558. inotify_rm_watch(inotify_fd, inotify_wd);
  2559. close(inotify_fd);
  2560. #elif defined(BSD_KQUEUE)
  2561. if (event_fd >= 0)
  2562. close(event_fd);
  2563. close(kq);
  2564. #endif
  2565. #ifdef DEBUGMODE
  2566. disabledbg();
  2567. #endif
  2568. exit(0);
  2569. }