My build of nnn with minor changes
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

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