My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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