My build of nnn with minor changes
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

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