My build of nnn with minor changes
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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