My build of nnn with minor changes
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

3486 lines
74 KiB

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