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

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