My build of nnn with minor changes
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

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