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

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