My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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