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

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