My build of nnn with minor changes
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

3507 řádky
76 KiB

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