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

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