My build of nnn with minor changes
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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