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.
 
 
 
 
 
 

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