My build of nnn with minor changes
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

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