My build of nnn with minor changes
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

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