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.
 
 
 
 
 
 

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