My build of nnn with minor changes
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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