My build of nnn with minor changes
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

3476 строки
74 KiB

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