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.
 
 
 
 
 
 

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