My build of nnn with minor changes
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

3507 рядки
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. if (!s)
  393. return 0;
  394. len = 0;
  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. static char *
  1127. readinput(void)
  1128. {
  1129. cleartimeout();
  1130. echo();
  1131. curs_set(TRUE);
  1132. memset(g_buf, 0, NAME_MAX + 1);
  1133. wgetnstr(stdscr, g_buf, NAME_MAX);
  1134. noecho();
  1135. curs_set(FALSE);
  1136. settimeout();
  1137. return g_buf[0] ? g_buf : NULL;
  1138. }
  1139. /*
  1140. * Updates out with "dir/name or "/name"
  1141. * Returns the number of bytes copied including the terminating NULL byte
  1142. */
  1143. static size_t
  1144. mkpath(char *dir, char *name, char *out, size_t n)
  1145. {
  1146. static size_t len;
  1147. /* Handle absolute path */
  1148. if (name[0] == '/')
  1149. return xstrlcpy(out, name, n);
  1150. else {
  1151. /* Handle root case */
  1152. if (istopdir(dir))
  1153. len = 1;
  1154. else
  1155. len = xstrlcpy(out, dir, n);
  1156. }
  1157. out[len - 1] = '/';
  1158. return (xstrlcpy(out + len, name, n - len) + len);
  1159. }
  1160. static void
  1161. parsebmstr(char *bms)
  1162. {
  1163. int i = 0;
  1164. while (*bms && i < BM_MAX) {
  1165. bookmark[i].key = bms;
  1166. ++bms;
  1167. while (*bms && *bms != ':')
  1168. ++bms;
  1169. if (!*bms) {
  1170. bookmark[i].key = NULL;
  1171. break;
  1172. }
  1173. *bms = '\0';
  1174. bookmark[i].loc = ++bms;
  1175. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  1176. bookmark[i].key = NULL;
  1177. break;
  1178. }
  1179. while (*bms && *bms != ';')
  1180. ++bms;
  1181. if (*bms)
  1182. *bms = '\0';
  1183. else
  1184. break;
  1185. ++bms;
  1186. ++i;
  1187. }
  1188. }
  1189. /*
  1190. * Get the real path to a bookmark
  1191. *
  1192. * NULL is returned in case of no match, path resolution failure etc.
  1193. * buf would be modified, so check return value before access
  1194. */
  1195. static char *
  1196. get_bm_loc(char *key, char *buf)
  1197. {
  1198. int r;
  1199. if (!key || !key[0])
  1200. return NULL;
  1201. for (r = 0; bookmark[r].key && r < BM_MAX; ++r) {
  1202. if (xstrcmp(bookmark[r].key, key) == 0) {
  1203. if (bookmark[r].loc[0] == '~') {
  1204. char *home = getenv("HOME");
  1205. if (!home) {
  1206. DPRINTF_S(messages[STR_NOHOME_ID]);
  1207. return NULL;
  1208. }
  1209. snprintf(buf, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  1210. } else
  1211. xstrlcpy(buf, bookmark[r].loc, PATH_MAX);
  1212. return buf;
  1213. }
  1214. }
  1215. DPRINTF_S("Invalid key");
  1216. return NULL;
  1217. }
  1218. static void
  1219. resetdircolor(mode_t mode)
  1220. {
  1221. if (cfg.dircolor && !S_ISDIR(mode)) {
  1222. attroff(COLOR_PAIR(1) | A_BOLD);
  1223. cfg.dircolor = 0;
  1224. }
  1225. }
  1226. /*
  1227. * Replace escape characters in a string with '?'
  1228. * Adjust string length to maxcols if > 0;
  1229. *
  1230. * Interestingly, note that unescape() uses g_buf. What happens if
  1231. * str also points to g_buf? In this case we assume that the caller
  1232. * acknowledges that it's OK to lose the data in g_buf after this
  1233. * call to unescape().
  1234. * The API, on its part, first converts str to multibyte (after which
  1235. * it doesn't touch str anymore). Only after that it starts modifying
  1236. * g_buf. This is a phased operation.
  1237. */
  1238. static char *
  1239. unescape(const char *str, uint maxcols)
  1240. {
  1241. static wchar_t wbuf[PATH_MAX] __attribute__ ((aligned));
  1242. static wchar_t *buf;
  1243. static size_t len;
  1244. /* Convert multi-byte to wide char */
  1245. len = mbstowcs(wbuf, str, PATH_MAX);
  1246. g_buf[0] = '\0';
  1247. buf = wbuf;
  1248. if (maxcols && len > maxcols) {
  1249. len = wcswidth(wbuf, len);
  1250. if (len > maxcols)
  1251. wbuf[maxcols] = 0;
  1252. }
  1253. while (*buf) {
  1254. if (*buf <= '\x1f' || *buf == '\x7f')
  1255. *buf = '\?';
  1256. ++buf;
  1257. }
  1258. /* Convert wide char to multi-byte */
  1259. wcstombs(g_buf, wbuf, PATH_MAX);
  1260. return g_buf;
  1261. }
  1262. static char *
  1263. coolsize(off_t size)
  1264. {
  1265. static const char * const U = "BKMGTPEZY";
  1266. static char size_buf[12]; /* Buffer to hold human readable size */
  1267. static off_t rem;
  1268. static int i;
  1269. i = 0;
  1270. rem = 0;
  1271. while (size > 1024) {
  1272. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  1273. size >>= 10;
  1274. ++i;
  1275. }
  1276. if (i == 1) {
  1277. rem = (rem * 1000) >> 10;
  1278. rem /= 10;
  1279. if (rem % 10 >= 5) {
  1280. rem = (rem / 10) + 1;
  1281. if (rem == 10) {
  1282. ++size;
  1283. rem = 0;
  1284. }
  1285. } else
  1286. rem /= 10;
  1287. } else if (i == 2) {
  1288. rem = (rem * 1000) >> 10;
  1289. if (rem % 10 >= 5) {
  1290. rem = (rem / 10) + 1;
  1291. if (rem == 100) {
  1292. ++size;
  1293. rem = 0;
  1294. }
  1295. } else
  1296. rem /= 10;
  1297. } else if (i > 0) {
  1298. rem = (rem * 10000) >> 10;
  1299. if (rem % 10 >= 5) {
  1300. rem = (rem / 10) + 1;
  1301. if (rem == 1000) {
  1302. ++size;
  1303. rem = 0;
  1304. }
  1305. } else
  1306. rem /= 10;
  1307. }
  1308. if (i > 0)
  1309. snprintf(size_buf, 12, "%lu.%0*lu%c", (ulong)size, i, (ulong)rem, U[i]);
  1310. else
  1311. snprintf(size_buf, 12, "%lu%c", (ulong)size, U[i]);
  1312. return size_buf;
  1313. }
  1314. static char *
  1315. get_file_sym(mode_t mode)
  1316. {
  1317. static char ind[2] = "\0\0";
  1318. if (S_ISDIR(mode))
  1319. ind[0] = '/';
  1320. else if (S_ISLNK(mode))
  1321. ind[0] = '@';
  1322. else if (S_ISSOCK(mode))
  1323. ind[0] = '=';
  1324. else if (S_ISFIFO(mode))
  1325. ind[0] = '|';
  1326. else if (mode & 0100)
  1327. ind[0] = '*';
  1328. else
  1329. ind[0] = '\0';
  1330. return ind;
  1331. }
  1332. static void
  1333. printent(struct entry *ent, int sel, uint namecols)
  1334. {
  1335. static char *pname;
  1336. pname = unescape(ent->name, namecols);
  1337. /* Directories are always shown on top */
  1338. resetdircolor(ent->mode);
  1339. printw("%s%s%s\n", CURSYM(sel), pname, get_file_sym(ent->mode));
  1340. }
  1341. static void
  1342. printent_long(struct entry *ent, int sel, uint namecols)
  1343. {
  1344. static char buf[18], *pname;
  1345. strftime(buf, 18, "%F %R", localtime(&ent->t));
  1346. pname = unescape(ent->name, namecols);
  1347. /* Directories are always shown on top */
  1348. resetdircolor(ent->mode);
  1349. if (sel)
  1350. attron(A_REVERSE);
  1351. if (S_ISDIR(ent->mode)) {
  1352. if (cfg.blkorder)
  1353. printw("%s%-16.16s %8.8s/ %s/\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1354. else
  1355. printw("%s%-16.16s / %s/\n", CURSYM(sel), buf, pname);
  1356. } else if (S_ISLNK(ent->mode))
  1357. printw("%s%-16.16s @ %s@\n", CURSYM(sel), buf, pname);
  1358. else if (S_ISSOCK(ent->mode))
  1359. printw("%s%-16.16s = %s=\n", CURSYM(sel), buf, pname);
  1360. else if (S_ISFIFO(ent->mode))
  1361. printw("%s%-16.16s | %s|\n", CURSYM(sel), buf, pname);
  1362. else if (S_ISBLK(ent->mode))
  1363. printw("%s%-16.16s b %s\n", CURSYM(sel), buf, pname);
  1364. else if (S_ISCHR(ent->mode))
  1365. printw("%s%-16.16s c %s\n", CURSYM(sel), buf, pname);
  1366. else if (ent->mode & 0100) {
  1367. if (cfg.blkorder)
  1368. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1369. else
  1370. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1371. } else {
  1372. if (cfg.blkorder)
  1373. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1374. else
  1375. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1376. }
  1377. if (sel)
  1378. attroff(A_REVERSE);
  1379. }
  1380. static void (*printptr)(struct entry *ent, int sel, uint namecols) = &printent_long;
  1381. static char
  1382. get_fileind(mode_t mode, char *desc)
  1383. {
  1384. static char c;
  1385. if (S_ISREG(mode)) {
  1386. c = '-';
  1387. xstrlcpy(desc, "regular file", DESCRIPTOR_LEN);
  1388. if (mode & 0100)
  1389. xstrlcpy(desc + 12, ", executable", DESCRIPTOR_LEN - 12); /* Length of string "regular file" is 12 */
  1390. } else if (S_ISDIR(mode)) {
  1391. c = 'd';
  1392. xstrlcpy(desc, "directory", DESCRIPTOR_LEN);
  1393. } else if (S_ISBLK(mode)) {
  1394. c = 'b';
  1395. xstrlcpy(desc, "block special device", DESCRIPTOR_LEN);
  1396. } else if (S_ISCHR(mode)) {
  1397. c = 'c';
  1398. xstrlcpy(desc, "character special device", DESCRIPTOR_LEN);
  1399. #ifdef S_ISFIFO
  1400. } else if (S_ISFIFO(mode)) {
  1401. c = 'p';
  1402. xstrlcpy(desc, "FIFO", DESCRIPTOR_LEN);
  1403. #endif /* S_ISFIFO */
  1404. #ifdef S_ISLNK
  1405. } else if (S_ISLNK(mode)) {
  1406. c = 'l';
  1407. xstrlcpy(desc, "symbolic link", DESCRIPTOR_LEN);
  1408. #endif /* S_ISLNK */
  1409. #ifdef S_ISSOCK
  1410. } else if (S_ISSOCK(mode)) {
  1411. c = 's';
  1412. xstrlcpy(desc, "socket", DESCRIPTOR_LEN);
  1413. #endif /* S_ISSOCK */
  1414. #ifdef S_ISDOOR
  1415. /* Solaris 2.6, etc. */
  1416. } else if (S_ISDOOR(mode)) {
  1417. c = 'D';
  1418. desc[0] = '\0';
  1419. #endif /* S_ISDOOR */
  1420. } else {
  1421. /* Unknown type -- possibly a regular file? */
  1422. c = '?';
  1423. desc[0] = '\0';
  1424. }
  1425. return c;
  1426. }
  1427. /* Convert a mode field into "ls -l" type perms field. */
  1428. static char *
  1429. get_lsperms(mode_t mode, char *desc)
  1430. {
  1431. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1432. static char bits[11] = {'\0'};
  1433. bits[0] = get_fileind(mode, desc);
  1434. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  1435. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  1436. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  1437. if (mode & S_ISUID)
  1438. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1439. if (mode & S_ISGID)
  1440. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1441. if (mode & S_ISVTX)
  1442. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1443. return bits;
  1444. }
  1445. /*
  1446. * Gets only a single line (that's what we need
  1447. * for now) or shows full command output in pager.
  1448. *
  1449. * If pager is valid, returns NULL
  1450. */
  1451. static char *
  1452. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager)
  1453. {
  1454. pid_t pid;
  1455. int pipefd[2];
  1456. FILE *pf;
  1457. int tmp, flags;
  1458. char *ret = NULL;
  1459. if (pipe(pipefd) == -1)
  1460. errexit();
  1461. for (tmp = 0; tmp < 2; ++tmp) {
  1462. /* Get previous flags */
  1463. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1464. /* Set bit for non-blocking flag */
  1465. flags |= O_NONBLOCK;
  1466. /* Change flags on fd */
  1467. fcntl(pipefd[tmp], F_SETFL, flags);
  1468. }
  1469. pid = fork();
  1470. if (pid == 0) {
  1471. /* In child */
  1472. close(pipefd[0]);
  1473. dup2(pipefd[1], STDOUT_FILENO);
  1474. dup2(pipefd[1], STDERR_FILENO);
  1475. close(pipefd[1]);
  1476. execlp(file, file, arg1, arg2, NULL);
  1477. _exit(1);
  1478. }
  1479. /* In parent */
  1480. waitpid(pid, &tmp, 0);
  1481. close(pipefd[1]);
  1482. if (!pager) {
  1483. pf = fdopen(pipefd[0], "r");
  1484. if (pf) {
  1485. ret = fgets(buf, bytes, pf);
  1486. close(pipefd[0]);
  1487. }
  1488. return ret;
  1489. }
  1490. pid = fork();
  1491. if (pid == 0) {
  1492. /* Show in pager in child */
  1493. dup2(pipefd[0], STDIN_FILENO);
  1494. close(pipefd[0]);
  1495. execlp("less", "less", NULL);
  1496. _exit(1);
  1497. }
  1498. /* In parent */
  1499. waitpid(pid, &tmp, 0);
  1500. close(pipefd[0]);
  1501. return NULL;
  1502. }
  1503. /*
  1504. * Follows the stat(1) output closely
  1505. */
  1506. static int
  1507. show_stats(char *fpath, char *fname, struct stat *sb)
  1508. {
  1509. char desc[DESCRIPTOR_LEN];
  1510. char *perms = get_lsperms(sb->st_mode, desc);
  1511. char *p, *begin = g_buf;
  1512. char tmp[] = "/tmp/nnnXXXXXX";
  1513. int fd = mkstemp(tmp);
  1514. if (fd == -1)
  1515. return -1;
  1516. dprintf(fd, " File: '%s'", unescape(fname, 0));
  1517. /* Show file name or 'symlink' -> 'target' */
  1518. if (perms[0] == 'l') {
  1519. /* Note that MAX_CMD_LEN > PATH_MAX */
  1520. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1521. if (len != -1) {
  1522. g_buf[len] = '\0';
  1523. /*
  1524. * We pass g_buf but unescape() operates on g_buf too!
  1525. * Read the API notes for information on how this works.
  1526. */
  1527. dprintf(fd, " -> '%s'", unescape(g_buf, 0));
  1528. }
  1529. }
  1530. /* Show size, blocks, file type */
  1531. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1532. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1533. (long long)sb->st_size, (long long)sb->st_blocks, sb->st_blksize, desc);
  1534. #else
  1535. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1536. sb->st_size, sb->st_blocks, (long)sb->st_blksize, desc);
  1537. #endif
  1538. /* Show containing device, inode, hardlink count */
  1539. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1540. snprintf(g_buf, 32, "%xh/%ud", sb->st_dev, sb->st_dev);
  1541. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1542. g_buf, (unsigned long long)sb->st_ino, sb->st_nlink);
  1543. #else
  1544. snprintf(g_buf, 32, "%lxh/%lud", (ulong)sb->st_dev, (ulong)sb->st_dev);
  1545. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1546. g_buf, sb->st_ino, (ulong)sb->st_nlink);
  1547. #endif
  1548. /* Show major, minor number for block or char device */
  1549. if (perms[0] == 'b' || perms[0] == 'c')
  1550. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1551. /* Show permissions, owner, group */
  1552. 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,
  1553. sb->st_mode & 7, perms, sb->st_uid, (getpwuid(sb->st_uid))->pw_name, sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1554. /* Show last access time */
  1555. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_atime));
  1556. dprintf(fd, "\n\n Access: %s", g_buf);
  1557. /* Show last modification time */
  1558. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_mtime));
  1559. dprintf(fd, "\n Modify: %s", g_buf);
  1560. /* Show last status change time */
  1561. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_ctime));
  1562. dprintf(fd, "\n Change: %s", g_buf);
  1563. if (S_ISREG(sb->st_mode)) {
  1564. /* Show file(1) output */
  1565. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1566. if (p) {
  1567. dprintf(fd, "\n\n ");
  1568. while (*p) {
  1569. if (*p == ',') {
  1570. *p = '\0';
  1571. dprintf(fd, " %s\n", begin);
  1572. begin = p + 1;
  1573. }
  1574. ++p;
  1575. }
  1576. dprintf(fd, " %s", begin);
  1577. }
  1578. dprintf(fd, "\n\n");
  1579. } else
  1580. dprintf(fd, "\n\n\n");
  1581. close(fd);
  1582. exitcurses();
  1583. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1584. unlink(tmp);
  1585. refresh();
  1586. return 0;
  1587. }
  1588. static size_t
  1589. get_fs_free(const char *path)
  1590. {
  1591. static struct statvfs svb;
  1592. if (statvfs(path, &svb) == -1)
  1593. return 0;
  1594. else
  1595. return svb.f_bavail << ffs(svb.f_frsize >> 1);
  1596. }
  1597. static size_t
  1598. get_fs_capacity(const char *path)
  1599. {
  1600. struct statvfs svb;
  1601. if (statvfs(path, &svb) == -1)
  1602. return 0;
  1603. else
  1604. return svb.f_blocks << ffs(svb.f_bsize >> 1);
  1605. }
  1606. static int
  1607. show_mediainfo(char *fpath, char *arg)
  1608. {
  1609. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[cfg.metaviewer], NULL, 0))
  1610. return -1;
  1611. exitcurses();
  1612. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, 1);
  1613. refresh();
  1614. return 0;
  1615. }
  1616. static int
  1617. handle_archive(char *fpath, char *arg, char *dir)
  1618. {
  1619. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[ATOOL], NULL, 0))
  1620. return -1;
  1621. if (arg[1] == 'x')
  1622. spawn(utils[ATOOL], arg, fpath, dir, F_NORMAL);
  1623. else {
  1624. exitcurses();
  1625. get_output(NULL, 0, utils[ATOOL], arg, fpath, 1);
  1626. refresh();
  1627. }
  1628. return 0;
  1629. }
  1630. /*
  1631. * The help string tokens (each line) start with a HEX value
  1632. * which indicates the number of spaces to print before the
  1633. * particular token. This method was chosen instead of a flat
  1634. * string because the number of bytes in help was increasing
  1635. * the binary size by around a hundred bytes. This would only
  1636. * have increased as we keep adding new options.
  1637. */
  1638. static int
  1639. show_help(char *path)
  1640. {
  1641. char tmp[] = "/tmp/nnnXXXXXX";
  1642. int i = 0, fd = mkstemp(tmp);
  1643. char *start, *end;
  1644. static char helpstr[] = {
  1645. "cKey | Function\n"
  1646. "e- + -\n"
  1647. "7↑, k, ^P | Prev entry\n"
  1648. "7↓, j, ^N | Next entry\n"
  1649. "7PgUp, ^U | Scroll half page up\n"
  1650. "7PgDn, ^D | Scroll half page down\n"
  1651. "1Home, g, ^, ^A | First entry\n"
  1652. "2End, G, $, ^E | Last entry\n"
  1653. "4→, ↵, l, ^M | Open file/enter dir\n"
  1654. "1←, Bksp, h, ^H | Parent dir\n"
  1655. "d^O | Open with...\n"
  1656. "5Insert, ^I | Toggle nav-as-you-type\n"
  1657. "e~ | Go HOME\n"
  1658. "e& | Start-up dir\n"
  1659. "e- | Last visited dir\n"
  1660. "e/ | Filter entries\n"
  1661. "d^/ | Open desktop search app\n"
  1662. "e. | Toggle show . files\n"
  1663. "d^B | Bookmark prompt\n"
  1664. "eb | Pin current dir\n"
  1665. "d^V | Go to pinned dir\n"
  1666. "ec | Change dir prompt\n"
  1667. "ed | Toggle detail view\n"
  1668. "eD | File details\n"
  1669. "em | Brief media info\n"
  1670. "eM | Full media info\n"
  1671. "en | Create new\n"
  1672. "d^R | Rename entry\n"
  1673. "er | Open dir in vidir\n"
  1674. "es | Toggle sort by size\n"
  1675. "aS, ^J | Toggle du mode\n"
  1676. "et | Toggle sort by mtime\n"
  1677. "a!, ^] | Spawn SHELL in dir\n"
  1678. "eR | Run custom script\n"
  1679. "ee | Edit entry in EDITOR\n"
  1680. "eo | Open DE filemanager\n"
  1681. "ep | Open entry in PAGER\n"
  1682. "ef | Archive entry\n"
  1683. "eF | List archive\n"
  1684. "d^F | Extract archive\n"
  1685. "d^K | Copy file path\n"
  1686. "d^Y | Toggle multi-copy\n"
  1687. "d^T | Toggle path quote\n"
  1688. "d^L | Redraw, clear prompt\n"
  1689. #ifdef __linux__
  1690. "eL | Lock terminal\n"
  1691. #endif
  1692. "e? | Help, settings\n"
  1693. "aQ, ^G | Quit and cd\n"
  1694. "aq, ^X | Quit\n\n"};
  1695. if (fd == -1)
  1696. return -1;
  1697. start = end = helpstr;
  1698. while (*end) {
  1699. while (*end != '\n')
  1700. ++end;
  1701. if (start == end) {
  1702. ++end;
  1703. continue;
  1704. }
  1705. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1706. start = ++end;
  1707. }
  1708. dprintf(fd, "\nVolume: %s of ", coolsize(get_fs_free(path)));
  1709. dprintf(fd, "%s free\n\n", coolsize(get_fs_capacity(path)));
  1710. if (getenv("NNN_BMS")) {
  1711. dprintf(fd, "BOOKMARKS\n");
  1712. for (; i < BM_MAX; ++i)
  1713. if (bookmark[i].key)
  1714. dprintf(fd, " %s: %s\n", bookmark[i].key, bookmark[i].loc);
  1715. else
  1716. break;
  1717. dprintf(fd, "\n");
  1718. }
  1719. if (editor)
  1720. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1721. if (desktop_manager)
  1722. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1723. if (idletimeout)
  1724. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1725. if (copier)
  1726. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1727. if (getenv("NNN_NO_X"))
  1728. dprintf(fd, "NNN_NO_X: %s\n", getenv("NNN_NO_X"));
  1729. if (getenv("NNN_SCRIPT"))
  1730. dprintf(fd, "NNN_SCRIPT: %s\n", getenv("NNN_SCRIPT"));
  1731. if (getenv("NNN_SHOW_HIDDEN"))
  1732. dprintf(fd, "NNN_SHOW_HIDDEN: %s\n", getenv("NNN_SHOW_HIDDEN"));
  1733. dprintf(fd, "\n");
  1734. if (getenv("PWD"))
  1735. dprintf(fd, "PWD: %s\n", getenv("PWD"));
  1736. if (getenv("SHELL"))
  1737. dprintf(fd, "SHELL: %s\n", getenv("SHELL"));
  1738. if (getenv("SHLVL"))
  1739. dprintf(fd, "SHLVL: %s\n", getenv("SHLVL"));
  1740. if (getenv("VISUAL"))
  1741. dprintf(fd, "VISUAL: %s\n", getenv("VISUAL"));
  1742. else if (getenv("EDITOR"))
  1743. dprintf(fd, "EDITOR: %s\n", getenv("EDITOR"));
  1744. if (getenv("PAGER"))
  1745. dprintf(fd, "PAGER: %s\n", getenv("PAGER"));
  1746. dprintf(fd, "\nVersion: %s\n%s\n", VERSION, GENERAL_INFO);
  1747. close(fd);
  1748. exitcurses();
  1749. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1750. unlink(tmp);
  1751. refresh();
  1752. return 0;
  1753. }
  1754. static int
  1755. sum_bsizes(const char *fpath, const struct stat *sb,
  1756. int typeflag, struct FTW *ftwbuf)
  1757. {
  1758. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1759. ent_blocks += sb->st_blocks;
  1760. ++num_files;
  1761. return 0;
  1762. }
  1763. static int
  1764. dentfill(char *path, struct entry **dents,
  1765. int (*filter)(regex_t *, char *), regex_t *re)
  1766. {
  1767. static DIR *dirp;
  1768. static struct dirent *dp;
  1769. static char *namep, *pnb;
  1770. static struct entry *dentp;
  1771. static size_t off, namebuflen = NAMEBUF_INCR;
  1772. static ulong num_saved;
  1773. static int fd, n, count;
  1774. static struct stat sb_path, sb;
  1775. off = 0;
  1776. dirp = opendir(path);
  1777. if (dirp == NULL)
  1778. return 0;
  1779. fd = dirfd(dirp);
  1780. n = 0;
  1781. if (cfg.blkorder) {
  1782. num_files = 0;
  1783. dir_blocks = 0;
  1784. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  1785. printwarn();
  1786. return 0;
  1787. }
  1788. }
  1789. while ((dp = readdir(dirp)) != NULL) {
  1790. namep = dp->d_name;
  1791. if (filter(re, namep) == 0) {
  1792. if (!cfg.blkorder)
  1793. continue;
  1794. /* Skip self and parent */
  1795. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  1796. continue;
  1797. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  1798. continue;
  1799. if (S_ISDIR(sb.st_mode)) {
  1800. if (sb_path.st_dev == sb.st_dev) {
  1801. ent_blocks = 0;
  1802. mkpath(path, namep, g_buf, PATH_MAX);
  1803. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1804. printmsg(messages[STR_NFTWFAIL_ID]);
  1805. dir_blocks += sb.st_blocks;
  1806. } else
  1807. dir_blocks += ent_blocks;
  1808. }
  1809. } else {
  1810. if (sb.st_blocks)
  1811. dir_blocks += sb.st_blocks;
  1812. ++num_files;
  1813. }
  1814. continue;
  1815. }
  1816. /* Skip self and parent */
  1817. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1818. (namep[1] == '.' && namep[2] == '\0'))))
  1819. continue;
  1820. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1821. DPRINTF_S(namep);
  1822. continue;
  1823. }
  1824. if (n == total_dents) {
  1825. total_dents += ENTRY_INCR;
  1826. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  1827. if (*dents == NULL) {
  1828. if (pnamebuf)
  1829. free(pnamebuf);
  1830. errexit();
  1831. }
  1832. DPRINTF_P(*dents);
  1833. }
  1834. /* If there's not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  1835. if (namebuflen - off < NAME_MAX + 1) {
  1836. namebuflen += NAMEBUF_INCR;
  1837. pnb = pnamebuf;
  1838. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  1839. if (pnamebuf == NULL) {
  1840. free(*dents);
  1841. errexit();
  1842. }
  1843. DPRINTF_P(pnamebuf);
  1844. /* realloc() may result in memory move, we must re-adjust if that happens */
  1845. if (pnb != pnamebuf) {
  1846. dentp = *dents;
  1847. dentp->name = pnamebuf;
  1848. for (count = 1; count < n; ++dentp, ++count)
  1849. /* Current filename starts at last filename start + length */
  1850. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  1851. }
  1852. }
  1853. dentp = *dents + n;
  1854. /* Copy file name */
  1855. dentp->name = (char *)((size_t)pnamebuf + off);
  1856. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  1857. off += dentp->nlen;
  1858. /* Copy other fields */
  1859. dentp->mode = sb.st_mode;
  1860. dentp->t = sb.st_mtime;
  1861. dentp->size = sb.st_size;
  1862. if (cfg.blkorder) {
  1863. if (S_ISDIR(sb.st_mode)) {
  1864. ent_blocks = 0;
  1865. num_saved = num_files + 1;
  1866. mkpath(path, namep, g_buf, PATH_MAX);
  1867. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1868. printmsg(messages[STR_NFTWFAIL_ID]);
  1869. dentp->blocks = sb.st_blocks;
  1870. } else
  1871. dentp->blocks = ent_blocks;
  1872. if (sb_path.st_dev == sb.st_dev)
  1873. dir_blocks += dentp->blocks;
  1874. else
  1875. num_files = num_saved;
  1876. } else {
  1877. dentp->blocks = sb.st_blocks;
  1878. dir_blocks += dentp->blocks;
  1879. ++num_files;
  1880. }
  1881. }
  1882. ++n;
  1883. }
  1884. /* Should never be null */
  1885. if (closedir(dirp) == -1) {
  1886. if (*dents) {
  1887. free(pnamebuf);
  1888. free(*dents);
  1889. }
  1890. errexit();
  1891. }
  1892. return n;
  1893. }
  1894. static void
  1895. dentfree(struct entry *dents)
  1896. {
  1897. free(pnamebuf);
  1898. free(dents);
  1899. }
  1900. /* Return the position of the matching entry or 0 otherwise */
  1901. static int
  1902. dentfind(struct entry *dents, const char *fname, int n)
  1903. {
  1904. static int i;
  1905. if (!fname)
  1906. return 0;
  1907. DPRINTF_S(fname);
  1908. for (i = 0; i < n; ++i)
  1909. if (xstrcmp(fname, dents[i].name) == 0)
  1910. return i;
  1911. return 0;
  1912. }
  1913. static int
  1914. populate(char *path, char *oldname, char *fltr)
  1915. {
  1916. static regex_t re;
  1917. /* Can fail when permissions change while browsing.
  1918. * It's assumed that path IS a directory when we are here.
  1919. */
  1920. if (access(path, R_OK) == -1)
  1921. return -1;
  1922. /* Search filter */
  1923. if (setfilter(&re, fltr) != 0)
  1924. return -1;
  1925. if (cfg.blkorder) {
  1926. printmsg("calculating...");
  1927. refresh();
  1928. }
  1929. #ifdef DEBUGMODE
  1930. struct timespec ts1, ts2;
  1931. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  1932. #endif
  1933. ndents = dentfill(path, &dents, visible, &re);
  1934. regfree(&re);
  1935. if (ndents == 0)
  1936. return 0;
  1937. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1938. #ifdef DEBUGMODE
  1939. clock_gettime(CLOCK_REALTIME, &ts2);
  1940. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  1941. #endif
  1942. /* Find cur from history */
  1943. cur = dentfind(dents, oldname, ndents);
  1944. return 0;
  1945. }
  1946. static void
  1947. redraw(char *path)
  1948. {
  1949. static char buf[(NAME_MAX + 1) << 1] __attribute__ ((aligned));
  1950. static size_t ncols;
  1951. static int nlines, i;
  1952. static bool mode_changed;
  1953. mode_changed = FALSE;
  1954. nlines = MIN(LINES - 4, ndents);
  1955. /* Clean screen */
  1956. erase();
  1957. if (cfg.copymode)
  1958. if (g_crc != crc8fast((uchar *)dents, ndents * sizeof(struct entry))) {
  1959. cfg.copymode = 0;
  1960. DPRINTF_S("copymode off");
  1961. }
  1962. /* Fail redraw if < than 10 columns */
  1963. if (COLS < 10) {
  1964. printmsg("too few columns!");
  1965. return;
  1966. }
  1967. /* Strip trailing slashes */
  1968. for (i = xstrlen(path) - 1; i > 0; --i)
  1969. if (path[i] == '/')
  1970. path[i] = '\0';
  1971. else
  1972. break;
  1973. DPRINTF_D(cur);
  1974. DPRINTF_S(path);
  1975. if (!realpath(path, g_buf)) {
  1976. printwarn();
  1977. return;
  1978. }
  1979. ncols = COLS;
  1980. if (ncols > PATH_MAX)
  1981. ncols = PATH_MAX;
  1982. /* No text wrapping in cwd line */
  1983. /* Show CWD: - xstrlen(CWD) - 1 = 6 */
  1984. g_buf[ncols - 6] = '\0';
  1985. printw(CWD "%s\n\n", g_buf);
  1986. /* Fallback to light mode if less than 35 columns */
  1987. if (ncols < 35 && cfg.showdetail) {
  1988. cfg.showdetail ^= 1;
  1989. printptr = &printent;
  1990. mode_changed = TRUE;
  1991. }
  1992. /* Calculate the number of cols available to print entry name */
  1993. if (cfg.showdetail)
  1994. ncols -= 32;
  1995. else
  1996. ncols -= 5;
  1997. if (cfg.showcolor) {
  1998. attron(COLOR_PAIR(1) | A_BOLD);
  1999. cfg.dircolor = 1;
  2000. }
  2001. /* Print listing */
  2002. if (cur < (nlines >> 1)) {
  2003. for (i = 0; i < nlines; ++i)
  2004. printptr(&dents[i], i == cur, ncols);
  2005. } else if (cur >= ndents - (nlines >> 1)) {
  2006. for (i = ndents - nlines; i < ndents; ++i)
  2007. printptr(&dents[i], i == cur, ncols);
  2008. } else {
  2009. static int odd;
  2010. odd = ISODD(nlines);
  2011. nlines >>= 1;
  2012. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  2013. printptr(&dents[i], i == cur, ncols);
  2014. }
  2015. /* Must reset e.g. no files in dir */
  2016. if (cfg.dircolor) {
  2017. attroff(COLOR_PAIR(1) | A_BOLD);
  2018. cfg.dircolor = 0;
  2019. }
  2020. if (cfg.showdetail) {
  2021. if (ndents) {
  2022. static char sort[9];
  2023. if (cfg.mtimeorder)
  2024. xstrlcpy(sort, "by time ", 9);
  2025. else if (cfg.sizeorder)
  2026. xstrlcpy(sort, "by size ", 9);
  2027. else
  2028. sort[0] = '\0';
  2029. /* We need to show filename as it may be truncated in directory listing */
  2030. if (!cfg.blkorder)
  2031. snprintf(buf, (NAME_MAX + 1) << 1, "%d/%d %s[%s%s]",
  2032. cur + 1, ndents, sort, unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  2033. else {
  2034. i = snprintf(buf, 128, "%d/%d du: %s (%lu files) ", cur + 1, ndents, coolsize(dir_blocks << 9), num_files);
  2035. snprintf(buf + i, ((NAME_MAX + 1) << 1) - 128, "vol: %s free [%s%s]",
  2036. coolsize(get_fs_free(path)), unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  2037. }
  2038. printmsg(buf);
  2039. } else
  2040. printmsg("0 items");
  2041. }
  2042. if (mode_changed) {
  2043. cfg.showdetail ^= 1;
  2044. printptr = &printent_long;
  2045. }
  2046. }
  2047. static void
  2048. browse(char *ipath, char *ifilter)
  2049. {
  2050. static char path[PATH_MAX] __attribute__ ((aligned));
  2051. static char newpath[PATH_MAX] __attribute__ ((aligned));
  2052. static char lastdir[PATH_MAX] __attribute__ ((aligned));
  2053. static char mark[PATH_MAX] __attribute__ ((aligned));
  2054. static char fltr[NAME_MAX + 1] __attribute__ ((aligned));
  2055. static char oldname[NAME_MAX + 1] __attribute__ ((aligned));
  2056. char *dir, *tmp, *run = NULL, *env = NULL;
  2057. struct stat sb;
  2058. int r, fd, presel, ncp, copystartid = 0, copyendid = 0;
  2059. enum action sel = SEL_RUNARG + 1;
  2060. bool dir_changed = FALSE;
  2061. xstrlcpy(path, ipath, PATH_MAX);
  2062. copyfilter();
  2063. oldname[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  2064. if (cfg.filtermode)
  2065. presel = FILTER;
  2066. else
  2067. presel = 0;
  2068. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  2069. if (dents == NULL)
  2070. errexit();
  2071. DPRINTF_P(dents);
  2072. /* Allocate buffer to hold names */
  2073. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  2074. if (pnamebuf == NULL) {
  2075. free(dents);
  2076. errexit();
  2077. }
  2078. DPRINTF_P(pnamebuf);
  2079. begin:
  2080. #ifdef LINUX_INOTIFY
  2081. if (dir_changed && inotify_wd >= 0) {
  2082. inotify_rm_watch(inotify_fd, inotify_wd);
  2083. inotify_wd = -1;
  2084. dir_changed = FALSE;
  2085. }
  2086. #elif defined(BSD_KQUEUE)
  2087. if (dir_changed && event_fd >= 0) {
  2088. close(event_fd);
  2089. event_fd = -1;
  2090. dir_changed = FALSE;
  2091. }
  2092. #endif
  2093. if (populate(path, oldname, fltr) == -1) {
  2094. printwarn();
  2095. goto nochange;
  2096. }
  2097. #ifdef LINUX_INOTIFY
  2098. if (inotify_wd == -1)
  2099. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  2100. #elif defined(BSD_KQUEUE)
  2101. if (event_fd == -1) {
  2102. #if defined(O_EVTONLY)
  2103. event_fd = open(path, O_EVTONLY);
  2104. #else
  2105. event_fd = open(path, O_RDONLY);
  2106. #endif
  2107. if (event_fd >= 0)
  2108. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  2109. }
  2110. #endif
  2111. for (;;) {
  2112. redraw(path);
  2113. nochange:
  2114. /* Exit if parent has exited */
  2115. if (getppid() == 1)
  2116. _exit(0);
  2117. sel = nextsel(&run, &env, &presel);
  2118. switch (sel) {
  2119. case SEL_BACK:
  2120. /* There is no going back */
  2121. if (istopdir(path)) {
  2122. printmsg(messages[STR_ATROOT_ID]);
  2123. goto nochange;
  2124. }
  2125. dir = xdirname(path);
  2126. if (access(dir, R_OK) == -1) {
  2127. printwarn();
  2128. goto nochange;
  2129. }
  2130. /* Save history */
  2131. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2132. /* Save last working directory */
  2133. xstrlcpy(lastdir, path, PATH_MAX);
  2134. dir_changed = TRUE;
  2135. xstrlcpy(path, dir, PATH_MAX);
  2136. /* Reset filter */
  2137. copyfilter();
  2138. if (cfg.filtermode)
  2139. presel = FILTER;
  2140. goto begin;
  2141. case SEL_GOIN:
  2142. /* Cannot descend in empty directories */
  2143. if (ndents == 0)
  2144. goto begin;
  2145. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2146. DPRINTF_S(newpath);
  2147. /* Get path info */
  2148. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  2149. if (fd == -1) {
  2150. printwarn();
  2151. goto nochange;
  2152. }
  2153. if (fstat(fd, &sb) == -1) {
  2154. printwarn();
  2155. close(fd);
  2156. goto nochange;
  2157. }
  2158. close(fd);
  2159. DPRINTF_U(sb.st_mode);
  2160. switch (sb.st_mode & S_IFMT) {
  2161. case S_IFDIR:
  2162. if (access(newpath, R_OK) == -1) {
  2163. printwarn();
  2164. goto nochange;
  2165. }
  2166. /* Save last working directory */
  2167. xstrlcpy(lastdir, path, PATH_MAX);
  2168. dir_changed = TRUE;
  2169. xstrlcpy(path, newpath, PATH_MAX);
  2170. oldname[0] = '\0';
  2171. /* Reset filter */
  2172. copyfilter();
  2173. if (cfg.filtermode)
  2174. presel = FILTER;
  2175. goto begin;
  2176. case S_IFREG:
  2177. {
  2178. /* If NNN_USE_EDITOR is set,
  2179. * open text in EDITOR
  2180. */
  2181. if (editor) {
  2182. if (getmime(dents[cur].name)) {
  2183. spawn(editor, newpath, NULL, path, F_NORMAL);
  2184. continue;
  2185. }
  2186. /* Recognize and open plain
  2187. * text files with vi
  2188. */
  2189. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  2190. continue;
  2191. if (strstr(g_buf, "text/") == g_buf) {
  2192. spawn(editor, newpath, NULL, path, F_NORMAL);
  2193. continue;
  2194. }
  2195. }
  2196. /* Invoke desktop opener as last resort */
  2197. spawn(utils[OPENER], newpath, NULL, NULL, F_NOWAIT | F_NOTRACE);
  2198. continue;
  2199. }
  2200. default:
  2201. printmsg("unsupported file");
  2202. goto nochange;
  2203. }
  2204. case SEL_NEXT:
  2205. if (cur < ndents - 1)
  2206. ++cur;
  2207. else if (ndents)
  2208. /* Roll over, set cursor to first entry */
  2209. cur = 0;
  2210. break;
  2211. case SEL_PREV:
  2212. if (cur > 0)
  2213. --cur;
  2214. else if (ndents)
  2215. /* Roll over, set cursor to last entry */
  2216. cur = ndents - 1;
  2217. break;
  2218. case SEL_PGDN:
  2219. if (cur < ndents - 1)
  2220. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  2221. break;
  2222. case SEL_PGUP:
  2223. if (cur > 0)
  2224. cur -= MIN((LINES - 4) / 2, cur);
  2225. break;
  2226. case SEL_HOME:
  2227. cur = 0;
  2228. break;
  2229. case SEL_END:
  2230. cur = ndents - 1;
  2231. break;
  2232. case SEL_CD:
  2233. {
  2234. char *input;
  2235. int truecd;
  2236. /* Save the program start dir */
  2237. tmp = getcwd(newpath, PATH_MAX);
  2238. if (tmp == NULL) {
  2239. printwarn();
  2240. goto nochange;
  2241. }
  2242. /* Switch to current path for readline(3) */
  2243. if (chdir(path) == -1) {
  2244. printwarn();
  2245. goto nochange;
  2246. }
  2247. exitcurses();
  2248. tmp = readline("chdir: ");
  2249. refresh();
  2250. /* Change back to program start dir */
  2251. if (chdir(newpath) == -1)
  2252. printwarn();
  2253. if (tmp[0] == '\0')
  2254. break;
  2255. /* Add to readline(3) history */
  2256. add_history(tmp);
  2257. input = tmp;
  2258. tmp = strstrip(tmp);
  2259. if (tmp[0] == '\0') {
  2260. free(input);
  2261. break;
  2262. }
  2263. truecd = 0;
  2264. if (tmp[0] == '~') {
  2265. /* Expand ~ to HOME absolute path */
  2266. char *home = getenv("HOME");
  2267. if (home)
  2268. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  2269. else {
  2270. free(input);
  2271. printmsg(messages[STR_NOHOME_ID]);
  2272. goto nochange;
  2273. }
  2274. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  2275. if (lastdir[0] == '\0') {
  2276. free(input);
  2277. break;
  2278. }
  2279. /* Switch to last visited dir */
  2280. xstrlcpy(newpath, lastdir, PATH_MAX);
  2281. truecd = 1;
  2282. } else if ((r = all_dots(tmp))) {
  2283. if (r == 1) {
  2284. /* Always in the current dir */
  2285. free(input);
  2286. break;
  2287. }
  2288. /* Show a message if already at / */
  2289. if (istopdir(path)) {
  2290. printmsg(messages[STR_ATROOT_ID]);
  2291. free(input);
  2292. goto nochange;
  2293. }
  2294. --r; /* One . for the current dir */
  2295. dir = path;
  2296. /* Note: fd is used as a tmp variable here */
  2297. for (fd = 0; fd < r; ++fd) {
  2298. /* Reached / ? */
  2299. if (istopdir(path)) {
  2300. /* Can't cd beyond / */
  2301. break;
  2302. }
  2303. dir = xdirname(dir);
  2304. if (access(dir, R_OK) == -1) {
  2305. printwarn();
  2306. free(input);
  2307. goto nochange;
  2308. }
  2309. }
  2310. truecd = 1;
  2311. /* Save the path in case of cd ..
  2312. * We mark the current dir in parent dir
  2313. */
  2314. if (r == 1) {
  2315. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2316. truecd = 2;
  2317. }
  2318. xstrlcpy(newpath, dir, PATH_MAX);
  2319. } else
  2320. mkpath(path, tmp, newpath, PATH_MAX);
  2321. free(input);
  2322. if (!xdiraccess(newpath))
  2323. goto nochange;
  2324. if (truecd == 0) {
  2325. /* Probable change in dir */
  2326. /* No-op if it's the same directory */
  2327. if (xstrcmp(path, newpath) == 0)
  2328. break;
  2329. oldname[0] = '\0';
  2330. } else if (truecd == 1)
  2331. /* Sure change in dir */
  2332. oldname[0] = '\0';
  2333. /* Save last working directory */
  2334. xstrlcpy(lastdir, path, PATH_MAX);
  2335. dir_changed = TRUE;
  2336. /* Save the newly opted dir in path */
  2337. xstrlcpy(path, newpath, PATH_MAX);
  2338. /* Reset filter */
  2339. copyfilter();
  2340. DPRINTF_S(path);
  2341. if (cfg.filtermode)
  2342. presel = FILTER;
  2343. goto begin;
  2344. }
  2345. case SEL_CDHOME:
  2346. dir = getenv("HOME");
  2347. if (dir == NULL) {
  2348. clearprompt();
  2349. goto nochange;
  2350. } // fallthrough
  2351. case SEL_CDBEGIN:
  2352. if (sel == SEL_CDBEGIN)
  2353. dir = ipath;
  2354. if (!xdiraccess(dir)) {
  2355. goto nochange;
  2356. }
  2357. if (xstrcmp(path, dir) == 0) {
  2358. break;
  2359. }
  2360. /* Save last working directory */
  2361. xstrlcpy(lastdir, path, PATH_MAX);
  2362. dir_changed = TRUE;
  2363. xstrlcpy(path, dir, PATH_MAX);
  2364. oldname[0] = '\0';
  2365. /* Reset filter */
  2366. copyfilter();
  2367. DPRINTF_S(path);
  2368. if (cfg.filtermode)
  2369. presel = FILTER;
  2370. goto begin;
  2371. case SEL_CDLAST: // fallthrough
  2372. case SEL_VISIT:
  2373. if (sel == SEL_VISIT) {
  2374. if (xstrcmp(mark, path) == 0)
  2375. break;
  2376. tmp = mark;
  2377. } else
  2378. tmp = lastdir;
  2379. if (tmp[0] == '\0') {
  2380. printmsg("not set...");
  2381. goto nochange;
  2382. }
  2383. if (!xdiraccess(tmp))
  2384. goto nochange;
  2385. xstrlcpy(newpath, tmp, PATH_MAX);
  2386. xstrlcpy(lastdir, path, PATH_MAX);
  2387. dir_changed = TRUE;
  2388. xstrlcpy(path, newpath, PATH_MAX);
  2389. oldname[0] = '\0';
  2390. /* Reset filter */
  2391. copyfilter();
  2392. DPRINTF_S(path);
  2393. if (cfg.filtermode)
  2394. presel = FILTER;
  2395. goto begin;
  2396. case SEL_CDBM:
  2397. printprompt("key: ");
  2398. tmp = readinput();
  2399. clearprompt();
  2400. if (tmp == NULL || tmp[0] == '\0')
  2401. break;
  2402. /* Interpret ~, - and & keys */
  2403. if ((tmp[1] == '\0') && (tmp[0] == '~' || tmp[0] == '-' || tmp[0] == '&')) {
  2404. presel = tmp[0];
  2405. goto begin;
  2406. }
  2407. if (get_bm_loc(tmp, newpath) == NULL) {
  2408. printmsg(messages[STR_INVBM_ID]);
  2409. goto nochange;
  2410. }
  2411. if (!xdiraccess(newpath))
  2412. goto nochange;
  2413. if (xstrcmp(path, newpath) == 0)
  2414. break;
  2415. oldname[0] = '\0';
  2416. /* Save last working directory */
  2417. xstrlcpy(lastdir, path, PATH_MAX);
  2418. dir_changed = TRUE;
  2419. /* Save the newly opted dir in path */
  2420. xstrlcpy(path, newpath, PATH_MAX);
  2421. /* Reset filter */
  2422. copyfilter();
  2423. DPRINTF_S(path);
  2424. if (cfg.filtermode)
  2425. presel = FILTER;
  2426. goto begin;
  2427. case SEL_PIN:
  2428. xstrlcpy(mark, path, PATH_MAX);
  2429. printmsg(mark);
  2430. goto nochange;
  2431. case SEL_FLTR:
  2432. presel = filterentries(path);
  2433. copyfilter();
  2434. DPRINTF_S(fltr);
  2435. /* Save current */
  2436. if (ndents > 0)
  2437. copycurname();
  2438. goto nochange;
  2439. case SEL_MFLTR:
  2440. cfg.filtermode ^= 1;
  2441. if (cfg.filtermode)
  2442. presel = FILTER;
  2443. else {
  2444. /* Save current */
  2445. if (ndents > 0)
  2446. copycurname();
  2447. /* Start watching the directory */
  2448. goto begin;
  2449. }
  2450. goto nochange;
  2451. case SEL_SEARCH:
  2452. spawn(player, path, "search", NULL, F_NORMAL);
  2453. break;
  2454. case SEL_TOGGLEDOT:
  2455. cfg.showhidden ^= 1;
  2456. initfilter(cfg.showhidden, &ifilter);
  2457. copyfilter();
  2458. goto begin;
  2459. case SEL_DETAIL:
  2460. cfg.showdetail ^= 1;
  2461. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2462. /* Save current */
  2463. if (ndents > 0)
  2464. copycurname();
  2465. goto begin;
  2466. case SEL_STATS:
  2467. if (ndents > 0) {
  2468. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2469. if (lstat(newpath, &sb) == -1) {
  2470. if (dents)
  2471. dentfree(dents);
  2472. errexit();
  2473. } else {
  2474. if (show_stats(newpath, dents[cur].name, &sb) < 0) {
  2475. printwarn();
  2476. goto nochange;
  2477. }
  2478. }
  2479. }
  2480. break;
  2481. case SEL_LIST: // fallthrough
  2482. case SEL_EXTRACT: // fallthrough
  2483. case SEL_MEDIA: // fallthrough
  2484. case SEL_FMEDIA:
  2485. if (ndents > 0) {
  2486. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2487. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2488. r = show_mediainfo(newpath, run);
  2489. else
  2490. r = handle_archive(newpath, run, path);
  2491. if (r == -1) {
  2492. xstrlcpy(newpath, "missing ", PATH_MAX);
  2493. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2494. xstrlcpy(newpath + 8, utils[cfg.metaviewer], 32);
  2495. else
  2496. xstrlcpy(newpath + 8, utils[ATOOL], 32);
  2497. printmsg(newpath);
  2498. goto nochange;
  2499. }
  2500. /* In case of successful archive extract, reload contents */
  2501. if (sel == SEL_EXTRACT) {
  2502. /* Continue in navigate-as-you-type mode, if enabled */
  2503. if (cfg.filtermode)
  2504. presel = FILTER;
  2505. /* Save current */
  2506. copycurname();
  2507. /* Repopulate as directory content may have changed */
  2508. goto begin;
  2509. }
  2510. }
  2511. break;
  2512. case SEL_DFB:
  2513. if (!desktop_manager) {
  2514. printmsg("set NNN_DE_FILE_MANAGER");
  2515. goto nochange;
  2516. }
  2517. spawn(desktop_manager, path, NULL, path, F_NOWAIT | F_NOTRACE);
  2518. break;
  2519. case SEL_FSIZE:
  2520. cfg.sizeorder ^= 1;
  2521. cfg.mtimeorder = 0;
  2522. cfg.blkorder = 0;
  2523. cfg.copymode = 0;
  2524. /* Save current */
  2525. if (ndents > 0)
  2526. copycurname();
  2527. goto begin;
  2528. case SEL_BSIZE:
  2529. cfg.blkorder ^= 1;
  2530. if (cfg.blkorder) {
  2531. cfg.showdetail = 1;
  2532. printptr = &printent_long;
  2533. }
  2534. cfg.mtimeorder = 0;
  2535. cfg.sizeorder = 0;
  2536. cfg.copymode = 0;
  2537. /* Save current */
  2538. if (ndents > 0)
  2539. copycurname();
  2540. goto begin;
  2541. case SEL_MTIME:
  2542. cfg.mtimeorder ^= 1;
  2543. cfg.sizeorder = 0;
  2544. cfg.blkorder = 0;
  2545. cfg.copymode = 0;
  2546. /* Save current */
  2547. if (ndents > 0)
  2548. copycurname();
  2549. goto begin;
  2550. case SEL_REDRAW:
  2551. /* Save current */
  2552. if (ndents > 0)
  2553. copycurname();
  2554. goto begin;
  2555. case SEL_COPY:
  2556. if (!(cfg.noxdisplay || copier))
  2557. printmsg(messages[STR_COPY_ID]);
  2558. else if (ndents) {
  2559. if (cfg.copymode) {
  2560. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2561. if (!appendfpath(newpath, r))
  2562. goto nochange;
  2563. ++ncp;
  2564. printmsg(newpath);
  2565. } else if (cfg.quote) {
  2566. g_buf[0] = '\'';
  2567. r = mkpath(path, dents[cur].name, g_buf + 1, PATH_MAX);
  2568. g_buf[r] = '\'';
  2569. g_buf[r + 1] = '\0';
  2570. if (cfg.noxdisplay)
  2571. writecp(g_buf, r + 1); /* Truncate NULL from end */
  2572. else
  2573. spawn(copier, g_buf, NULL, NULL, F_NOTRACE);
  2574. g_buf[r] = '\0';
  2575. printmsg(g_buf + 1);
  2576. } else {
  2577. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2578. if (cfg.noxdisplay)
  2579. writecp(newpath, r - 1); /* Truncate NULL from end */
  2580. else
  2581. spawn(copier, newpath, NULL, NULL, F_NOTRACE);
  2582. printmsg(newpath);
  2583. }
  2584. }
  2585. goto nochange;
  2586. case SEL_COPYMUL:
  2587. if (!(cfg.noxdisplay || copier))
  2588. printmsg(messages[STR_COPY_ID]);
  2589. else if (ndents) {
  2590. cfg.copymode ^= 1;
  2591. if (cfg.copymode) {
  2592. g_crc = crc8fast((uchar *)dents, ndents * sizeof(struct entry));
  2593. copystartid = cur;
  2594. copybufpos = 0;
  2595. ncp = 0;
  2596. printmsg("multi-copy on");
  2597. DPRINTF_S("copymode on");
  2598. } else {
  2599. if (!ncp) { /* Handle range selection */
  2600. if (cur < copystartid) {
  2601. copyendid = copystartid;
  2602. copystartid = cur;
  2603. } else
  2604. copyendid = cur;
  2605. if (copystartid < copyendid) {
  2606. for (r = copystartid; r <= copyendid; ++r)
  2607. if (!appendfpath(newpath, mkpath(path, dents[r].name, newpath, PATH_MAX)))
  2608. goto nochange;
  2609. snprintf(newpath, PATH_MAX, "%d files copied", copyendid - copystartid + 1);
  2610. printmsg(newpath);
  2611. }
  2612. }
  2613. if (copybufpos) { /* File path(s) written to the buffer */
  2614. if (cfg.noxdisplay)
  2615. writecp(pcopybuf, copybufpos - 1); /* Truncate NULL from end */
  2616. else
  2617. spawn(copier, pcopybuf, NULL, NULL, F_NOTRACE);
  2618. if (ncp) /* Some files cherry picked */
  2619. {
  2620. snprintf(newpath, PATH_MAX, "%d files copied", ncp);
  2621. printmsg(newpath);
  2622. }
  2623. } else
  2624. printmsg("multi-copy off");
  2625. }
  2626. }
  2627. goto nochange;
  2628. case SEL_QUOTE:
  2629. cfg.quote ^= 1;
  2630. DPRINTF_D(cfg.quote);
  2631. if (cfg.quote)
  2632. printmsg("quotes on");
  2633. else
  2634. printmsg("quotes off");
  2635. goto nochange;
  2636. case SEL_OPEN: // fallthrough
  2637. case SEL_ARCHIVE: // fallthrough
  2638. case SEL_NEW:
  2639. if (sel == SEL_OPEN)
  2640. tmp = xreadline(NULL, "open with: ");
  2641. else
  2642. tmp = xreadline(NULL, "name: ");
  2643. if (tmp == NULL || tmp[0] == '\0')
  2644. break;
  2645. /* Allow only relative, same dir paths */
  2646. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  2647. printmsg(messages[STR_INPUT_ID]);
  2648. goto nochange;
  2649. }
  2650. if (sel == SEL_OPEN) {
  2651. printprompt("press 'c' for cli mode");
  2652. cleartimeout();
  2653. r = getch();
  2654. settimeout();
  2655. if (r == 'c')
  2656. r = F_NORMAL;
  2657. else
  2658. r = F_NOWAIT | F_NOTRACE;
  2659. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2660. spawn(tmp, newpath, NULL, path, r);
  2661. continue;
  2662. } else if (sel == SEL_ARCHIVE) {
  2663. /* newpath is used as temporary buffer */
  2664. if (!get_output(newpath, PATH_MAX, "which", utils[APACK], NULL, 0)) {
  2665. printmsg("apack missing");
  2666. continue;
  2667. }
  2668. spawn(utils[APACK], tmp, dents[cur].name, path, F_NORMAL);
  2669. /* Continue in navigate-as-you-type mode, if enabled */
  2670. if (cfg.filtermode)
  2671. presel = FILTER;
  2672. /* Save current */
  2673. copycurname();
  2674. /* Repopulate as directory content may have changed */
  2675. goto begin;
  2676. }
  2677. /* Open the descriptor to currently open directory */
  2678. fd = open(path, O_RDONLY | O_DIRECTORY);
  2679. if (fd == -1) {
  2680. printwarn();
  2681. goto nochange;
  2682. }
  2683. /* Check if another file with same name exists */
  2684. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2685. printmsg("entry exists");
  2686. goto nochange;
  2687. }
  2688. /* Check if it's a dir or file */
  2689. printprompt("press 'f'(ile) or 'd'(ir)");
  2690. cleartimeout();
  2691. r = getch();
  2692. settimeout();
  2693. if (r == 'f') {
  2694. r = openat(fd, tmp, O_CREAT, 0666);
  2695. close(r);
  2696. } else if (r == 'd')
  2697. r = mkdirat(fd, tmp, 0777);
  2698. else {
  2699. close(fd);
  2700. break;
  2701. }
  2702. if (r == -1) {
  2703. printwarn();
  2704. close(fd);
  2705. goto nochange;
  2706. }
  2707. close(fd);
  2708. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2709. goto begin;
  2710. case SEL_RENAME:
  2711. if (ndents <= 0)
  2712. break;
  2713. tmp = xreadline(dents[cur].name, "");
  2714. if (tmp == NULL || tmp[0] == '\0')
  2715. break;
  2716. /* Allow only relative, same dir paths */
  2717. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  2718. printmsg(messages[STR_INPUT_ID]);
  2719. goto nochange;
  2720. }
  2721. /* Skip renaming to same name */
  2722. if (xstrcmp(tmp, dents[cur].name) == 0)
  2723. break;
  2724. /* Open the descriptor to currently open directory */
  2725. fd = open(path, O_RDONLY | O_DIRECTORY);
  2726. if (fd == -1) {
  2727. printwarn();
  2728. goto nochange;
  2729. }
  2730. /* Check if another file with same name exists */
  2731. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2732. /* File with the same name exists */
  2733. printprompt("press 'y' to overwrite");
  2734. cleartimeout();
  2735. r = getch();
  2736. settimeout();
  2737. if (r != 'y') {
  2738. close(fd);
  2739. break;
  2740. }
  2741. }
  2742. /* Rename the file */
  2743. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  2744. printwarn();
  2745. close(fd);
  2746. goto nochange;
  2747. }
  2748. close(fd);
  2749. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2750. goto begin;
  2751. case SEL_RENAMEALL:
  2752. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[VIDIR], NULL, 0)) {
  2753. printmsg("vidir missing");
  2754. goto nochange;
  2755. }
  2756. spawn(utils[VIDIR], ".", NULL, path, F_NORMAL);
  2757. /* Save current */
  2758. if (ndents > 0)
  2759. copycurname();
  2760. goto begin;
  2761. case SEL_HELP:
  2762. show_help(path);
  2763. /* Continue in navigate-as-you-type mode, if enabled */
  2764. if (cfg.filtermode)
  2765. presel = FILTER;
  2766. break;
  2767. case SEL_RUN: // fallthrough
  2768. case SEL_RUNSCRIPT:
  2769. run = xgetenv(env, run);
  2770. if (sel == SEL_RUNSCRIPT) {
  2771. tmp = getenv("NNN_SCRIPT");
  2772. if (tmp)
  2773. spawn(run, tmp, NULL, path, F_NORMAL | F_SIGINT);
  2774. } else {
  2775. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2776. /* Continue in navigate-as-you-type mode, if enabled */
  2777. if (cfg.filtermode)
  2778. presel = FILTER;
  2779. }
  2780. /* Save current */
  2781. if (ndents > 0)
  2782. copycurname();
  2783. /* Repopulate as directory content may have changed */
  2784. goto begin;
  2785. case SEL_RUNARG:
  2786. run = xgetenv(env, run);
  2787. if ((!run || !run[0]) && (xstrcmp("VISUAL", env) == 0))
  2788. run = editor ? editor : xgetenv("EDITOR", "vi");
  2789. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2790. break;
  2791. #ifdef __linux__
  2792. case SEL_LOCK:
  2793. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2794. break;
  2795. #endif
  2796. case SEL_CDQUIT:
  2797. {
  2798. char *tmpfile = "/tmp/nnn";
  2799. tmp = getenv("NNN_TMPFILE");
  2800. if (tmp)
  2801. tmpfile = tmp;
  2802. FILE *fp = fopen(tmpfile, "w");
  2803. if (fp) {
  2804. fprintf(fp, "cd \"%s\"", path);
  2805. fclose(fp);
  2806. }
  2807. /* Fall through to exit */
  2808. } // fallthrough
  2809. case SEL_QUIT:
  2810. dentfree(dents);
  2811. return;
  2812. } /* switch (sel) */
  2813. /* Screensaver */
  2814. if (idletimeout != 0 && idle == idletimeout) {
  2815. idle = 0;
  2816. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2817. }
  2818. }
  2819. }
  2820. static void
  2821. usage(void)
  2822. {
  2823. printf("usage: nnn [-b key] [-c N] [-e] [-i] [-l]\n\
  2824. [-p nlay] [-S] [-v] [-h] [PATH]\n\n\
  2825. The missing terminal file browser for X.\n\n\
  2826. positional arguments:\n\
  2827. PATH start dir [default: current dir]\n\n\
  2828. optional arguments:\n\
  2829. -b key specify bookmark key to open\n\
  2830. -c N specify dir color, disables if N>7\n\
  2831. -e use exiftool instead of mediainfo\n\
  2832. -i start in navigate-as-you-type mode\n\
  2833. -l start in light mode (fewer details)\n\
  2834. -p nlay path to custom nlay\n\
  2835. -S start in disk usage analyzer mode\n\
  2836. -v show program version and exit\n\
  2837. -h show this help and exit\n\n\
  2838. Version: %s\n%s\n", VERSION, GENERAL_INFO);
  2839. exit(0);
  2840. }
  2841. int
  2842. main(int argc, char *argv[])
  2843. {
  2844. static char cwd[PATH_MAX] __attribute__ ((aligned));
  2845. char *ipath = NULL, *ifilter, *bmstr;
  2846. int opt;
  2847. /* Confirm we are in a terminal */
  2848. if (!isatty(0) || !isatty(1)) {
  2849. fprintf(stderr, "stdin or stdout is not a tty\n");
  2850. exit(1);
  2851. }
  2852. while ((opt = getopt(argc, argv, "Slib:c:ep:vh")) != -1) {
  2853. switch (opt) {
  2854. case 'S':
  2855. cfg.blkorder = 1;
  2856. break;
  2857. case 'l':
  2858. cfg.showdetail = 0;
  2859. printptr = &printent;
  2860. break;
  2861. case 'i':
  2862. cfg.filtermode = 1;
  2863. break;
  2864. case 'b':
  2865. ipath = optarg;
  2866. break;
  2867. case 'c':
  2868. if (atoi(optarg) > 7)
  2869. cfg.showcolor = 0;
  2870. else
  2871. cfg.color = (uchar)atoi(optarg);
  2872. break;
  2873. case 'e':
  2874. cfg.metaviewer = EXIFTOOL;
  2875. break;
  2876. case 'p':
  2877. player = optarg;
  2878. break;
  2879. case 'v':
  2880. printf("%s\n", VERSION);
  2881. return 0;
  2882. case 'h': // fallthrough
  2883. default:
  2884. usage();
  2885. }
  2886. }
  2887. /* Parse bookmarks string, if available */
  2888. bmstr = getenv("NNN_BMS");
  2889. if (bmstr)
  2890. parsebmstr(bmstr);
  2891. if (ipath) { /* Open a bookmark directly */
  2892. if (get_bm_loc(ipath, cwd) == NULL) {
  2893. fprintf(stderr, "%s\n", messages[STR_INVBM_ID]);
  2894. exit(1);
  2895. }
  2896. ipath = cwd;
  2897. } else if (argc == optind) {
  2898. /* Start in the current directory */
  2899. ipath = getcwd(cwd, PATH_MAX);
  2900. if (ipath == NULL)
  2901. ipath = "/";
  2902. } else {
  2903. ipath = realpath(argv[optind], cwd);
  2904. if (!ipath) {
  2905. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2906. exit(1);
  2907. }
  2908. }
  2909. /* Increase current open file descriptor limit */
  2910. open_max = max_openfds();
  2911. if (getuid() == 0 || getenv("NNN_SHOW_HIDDEN"))
  2912. cfg.showhidden = 1;
  2913. initfilter(cfg.showhidden, &ifilter);
  2914. #ifdef LINUX_INOTIFY
  2915. /* Initialize inotify */
  2916. inotify_fd = inotify_init1(IN_NONBLOCK);
  2917. if (inotify_fd < 0) {
  2918. fprintf(stderr, "inotify init! %s\n", strerror(errno));
  2919. exit(1);
  2920. }
  2921. #elif defined(BSD_KQUEUE)
  2922. kq = kqueue();
  2923. if (kq < 0) {
  2924. fprintf(stderr, "kqueue init! %s\n", strerror(errno));
  2925. exit(1);
  2926. }
  2927. gtimeout.tv_sec = 0;
  2928. gtimeout.tv_nsec = 0;
  2929. #endif
  2930. /* Edit text in EDITOR, if opted */
  2931. if (getenv("NNN_USE_EDITOR")) {
  2932. editor = xgetenv("VISUAL", NULL);
  2933. if (!editor)
  2934. editor = xgetenv("EDITOR", "vi");
  2935. }
  2936. /* Set player if not set already */
  2937. if (!player)
  2938. player = utils[NLAY];
  2939. /* Get the desktop file browser, if set */
  2940. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2941. /* Get screensaver wait time, if set; copier used as tmp var */
  2942. copier = getenv("NNN_IDLE_TIMEOUT");
  2943. if (copier)
  2944. idletimeout = abs(atoi(copier));
  2945. /* Get the default copier, if set */
  2946. copier = getenv("NNN_COPIER");
  2947. /* Enable quotes if opted */
  2948. if (getenv("NNN_QUOTE_ON"))
  2949. cfg.quote = 1;
  2950. /* Check if X11 is available */
  2951. if (getenv("NNN_NO_X")) {
  2952. cfg.noxdisplay = 1;
  2953. struct passwd *pass = getpwuid(getuid());
  2954. xstrlcpy(g_cppath, "/tmp/nnncp", 11);
  2955. xstrlcpy(g_cppath + 10, pass->pw_name, 33);
  2956. }
  2957. signal(SIGINT, SIG_IGN);
  2958. /* Test initial path */
  2959. if (!xdiraccess(ipath)) {
  2960. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2961. exit(1);
  2962. }
  2963. /* Set locale */
  2964. setlocale(LC_ALL, "");
  2965. crc8init();
  2966. #ifdef DEBUGMODE
  2967. enabledbg();
  2968. #endif
  2969. initcurses();
  2970. browse(ipath, ifilter);
  2971. exitcurses();
  2972. #ifdef LINUX_INOTIFY
  2973. /* Shutdown inotify */
  2974. if (inotify_wd >= 0)
  2975. inotify_rm_watch(inotify_fd, inotify_wd);
  2976. close(inotify_fd);
  2977. #elif defined(BSD_KQUEUE)
  2978. if (event_fd >= 0)
  2979. close(event_fd);
  2980. close(kq);
  2981. #endif
  2982. #ifdef DEBUGMODE
  2983. disabledbg();
  2984. #endif
  2985. exit(0);
  2986. }