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

3427 lines
76 KiB

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