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

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