My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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