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.
 
 
 
 
 
 

3509 line
76 KiB

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