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.
 
 
 
 
 
 

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