My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

3490 lignes
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 || *ch == '\b') {
  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. switch (*ch) {
  1031. case KEY_ENTER: //fallthrough
  1032. case '\n': //fallthrough
  1033. case '\r':
  1034. goto END;
  1035. case '\b': /* some old curses (e.g. rhel25) still send '\b' for backspace */
  1036. if (pos > 0) {
  1037. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1038. --len, --pos;
  1039. } //fallthrough
  1040. case '\t': /* TAB breaks cursor position, ignore it */
  1041. continue;
  1042. case CONTROL('L'):
  1043. clearprompt();
  1044. printprompt(prompt);
  1045. len = pos = 0;
  1046. continue;
  1047. case CONTROL('A'):
  1048. pos = 0;
  1049. continue;
  1050. case CONTROL('E'):
  1051. pos = len;
  1052. continue;
  1053. case CONTROL('U'):
  1054. clearprompt();
  1055. printprompt(prompt);
  1056. memmove(buf, buf + pos, (len - pos) << 2);
  1057. len -= pos;
  1058. pos = 0;
  1059. continue;
  1060. }
  1061. /* Filter out all other control chars */
  1062. if (keyname(*ch)[0] == '^')
  1063. continue;
  1064. if (pos < NAME_MAX - 1) {
  1065. memmove(buf + pos + 1, buf + pos, (len - pos) << 2);
  1066. buf[pos] = *ch;
  1067. ++len, ++pos;
  1068. continue;
  1069. }
  1070. } else {
  1071. switch (*ch) {
  1072. case KEY_LEFT:
  1073. if (pos > 0)
  1074. --pos;
  1075. break;
  1076. case KEY_RIGHT:
  1077. if (pos < len)
  1078. ++pos;
  1079. break;
  1080. case KEY_BACKSPACE:
  1081. if (pos > 0) {
  1082. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1083. --len, --pos;
  1084. }
  1085. break;
  1086. case KEY_DC:
  1087. if (pos < len) {
  1088. memmove(buf + pos, buf + pos + 1, (len - pos - 1) << 2);
  1089. --len;
  1090. }
  1091. break;
  1092. default:
  1093. break;
  1094. }
  1095. }
  1096. }
  1097. }
  1098. END:
  1099. buf[len] = '\0';
  1100. if (old_curs != ERR)
  1101. curs_set(old_curs);
  1102. settimeout();
  1103. DPRINTF_S(buf);
  1104. wcstombs(g_buf, buf, NAME_MAX);
  1105. clearprompt();
  1106. return g_buf;
  1107. }
  1108. /*
  1109. * Updates out with "dir/name or "/name"
  1110. * Returns the number of bytes copied including the terminating NULL byte
  1111. */
  1112. static size_t
  1113. mkpath(char *dir, char *name, char *out, size_t n)
  1114. {
  1115. static size_t len;
  1116. /* Handle absolute path */
  1117. if (name[0] == '/')
  1118. return xstrlcpy(out, name, n);
  1119. else {
  1120. /* Handle root case */
  1121. if (istopdir(dir))
  1122. len = 1;
  1123. else
  1124. len = xstrlcpy(out, dir, n);
  1125. }
  1126. out[len - 1] = '/';
  1127. return (xstrlcpy(out + len, name, n - len) + len);
  1128. }
  1129. static void
  1130. parsebmstr(char *bms)
  1131. {
  1132. int i = 0;
  1133. while (*bms && i < BM_MAX) {
  1134. bookmark[i].key = bms;
  1135. ++bms;
  1136. while (*bms && *bms != ':')
  1137. ++bms;
  1138. if (!*bms) {
  1139. bookmark[i].key = NULL;
  1140. break;
  1141. }
  1142. *bms = '\0';
  1143. bookmark[i].loc = ++bms;
  1144. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  1145. bookmark[i].key = NULL;
  1146. break;
  1147. }
  1148. while (*bms && *bms != ';')
  1149. ++bms;
  1150. if (*bms)
  1151. *bms = '\0';
  1152. else
  1153. break;
  1154. ++bms;
  1155. ++i;
  1156. }
  1157. }
  1158. /*
  1159. * Get the real path to a bookmark
  1160. *
  1161. * NULL is returned in case of no match, path resolution failure etc.
  1162. * buf would be modified, so check return value before access
  1163. */
  1164. static char *
  1165. get_bm_loc(char *key, char *buf)
  1166. {
  1167. int r;
  1168. if (!key || !key[0])
  1169. return NULL;
  1170. for (r = 0; bookmark[r].key && r < BM_MAX; ++r) {
  1171. if (strcmp(bookmark[r].key, key) == 0) {
  1172. if (bookmark[r].loc[0] == '~') {
  1173. char *home = getenv("HOME");
  1174. if (!home) {
  1175. DPRINTF_S(messages[STR_NOHOME_ID]);
  1176. return NULL;
  1177. }
  1178. snprintf(buf, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  1179. } else
  1180. xstrlcpy(buf, bookmark[r].loc, PATH_MAX);
  1181. return buf;
  1182. }
  1183. }
  1184. DPRINTF_S("Invalid key");
  1185. return NULL;
  1186. }
  1187. static void
  1188. resetdircolor(mode_t mode)
  1189. {
  1190. if (cfg.dircolor && !S_ISDIR(mode)) {
  1191. attroff(COLOR_PAIR(1) | A_BOLD);
  1192. cfg.dircolor = 0;
  1193. }
  1194. }
  1195. /*
  1196. * Replace escape characters in a string with '?'
  1197. * Adjust string length to maxcols if > 0;
  1198. *
  1199. * Interestingly, note that unescape() uses g_buf. What happens if
  1200. * str also points to g_buf? In this case we assume that the caller
  1201. * acknowledges that it's OK to lose the data in g_buf after this
  1202. * call to unescape().
  1203. * The API, on its part, first converts str to multibyte (after which
  1204. * it doesn't touch str anymore). Only after that it starts modifying
  1205. * g_buf. This is a phased operation.
  1206. */
  1207. static char *
  1208. unescape(const char *str, uint maxcols)
  1209. {
  1210. static wchar_t wbuf[PATH_MAX] __attribute__ ((aligned));
  1211. static wchar_t *buf;
  1212. static size_t len;
  1213. /* Convert multi-byte to wide char */
  1214. len = mbstowcs(wbuf, str, PATH_MAX);
  1215. g_buf[0] = '\0';
  1216. buf = wbuf;
  1217. if (maxcols && len > maxcols) {
  1218. len = wcswidth(wbuf, len);
  1219. if (len > maxcols)
  1220. wbuf[maxcols] = 0;
  1221. }
  1222. while (*buf) {
  1223. if (*buf <= '\x1f' || *buf == '\x7f')
  1224. *buf = '\?';
  1225. ++buf;
  1226. }
  1227. /* Convert wide char to multi-byte */
  1228. wcstombs(g_buf, wbuf, PATH_MAX);
  1229. return g_buf;
  1230. }
  1231. static char *
  1232. coolsize(off_t size)
  1233. {
  1234. static const char * const U = "BKMGTPEZY";
  1235. static char size_buf[12]; /* Buffer to hold human readable size */
  1236. static off_t rem;
  1237. static int i;
  1238. i = 0;
  1239. rem = 0;
  1240. while (size > 1024) {
  1241. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  1242. size >>= 10;
  1243. ++i;
  1244. }
  1245. if (i == 1) {
  1246. rem = (rem * 1000) >> 10;
  1247. rem /= 10;
  1248. if (rem % 10 >= 5) {
  1249. rem = (rem / 10) + 1;
  1250. if (rem == 10) {
  1251. ++size;
  1252. rem = 0;
  1253. }
  1254. } else
  1255. rem /= 10;
  1256. } else if (i == 2) {
  1257. rem = (rem * 1000) >> 10;
  1258. if (rem % 10 >= 5) {
  1259. rem = (rem / 10) + 1;
  1260. if (rem == 100) {
  1261. ++size;
  1262. rem = 0;
  1263. }
  1264. } else
  1265. rem /= 10;
  1266. } else if (i > 0) {
  1267. rem = (rem * 10000) >> 10;
  1268. if (rem % 10 >= 5) {
  1269. rem = (rem / 10) + 1;
  1270. if (rem == 1000) {
  1271. ++size;
  1272. rem = 0;
  1273. }
  1274. } else
  1275. rem /= 10;
  1276. }
  1277. if (i > 0)
  1278. snprintf(size_buf, 12, "%lu.%0*lu%c", (ulong)size, i, (ulong)rem, U[i]);
  1279. else
  1280. snprintf(size_buf, 12, "%lu%c", (ulong)size, U[i]);
  1281. return size_buf;
  1282. }
  1283. static char *
  1284. get_file_sym(mode_t mode)
  1285. {
  1286. static char ind[2] = "\0\0";
  1287. if (S_ISDIR(mode))
  1288. ind[0] = '/';
  1289. else if (S_ISLNK(mode))
  1290. ind[0] = '@';
  1291. else if (S_ISSOCK(mode))
  1292. ind[0] = '=';
  1293. else if (S_ISFIFO(mode))
  1294. ind[0] = '|';
  1295. else if (mode & 0100)
  1296. ind[0] = '*';
  1297. else
  1298. ind[0] = '\0';
  1299. return ind;
  1300. }
  1301. static void
  1302. printent(struct entry *ent, int sel, uint namecols)
  1303. {
  1304. static char *pname;
  1305. pname = unescape(ent->name, namecols);
  1306. /* Directories are always shown on top */
  1307. resetdircolor(ent->mode);
  1308. printw("%s%s%s\n", CURSYM(sel), pname, get_file_sym(ent->mode));
  1309. }
  1310. static void
  1311. printent_long(struct entry *ent, int sel, uint namecols)
  1312. {
  1313. static char buf[18], *pname;
  1314. strftime(buf, 18, "%F %R", localtime(&ent->t));
  1315. pname = unescape(ent->name, namecols);
  1316. /* Directories are always shown on top */
  1317. resetdircolor(ent->mode);
  1318. if (sel)
  1319. attron(A_REVERSE);
  1320. if (S_ISDIR(ent->mode)) {
  1321. if (cfg.blkorder)
  1322. printw("%s%-16.16s %8.8s/ %s/\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1323. else
  1324. printw("%s%-16.16s / %s/\n", CURSYM(sel), buf, pname);
  1325. } else if (S_ISLNK(ent->mode))
  1326. printw("%s%-16.16s @ %s@\n", CURSYM(sel), buf, pname);
  1327. else if (S_ISSOCK(ent->mode))
  1328. printw("%s%-16.16s = %s=\n", CURSYM(sel), buf, pname);
  1329. else if (S_ISFIFO(ent->mode))
  1330. printw("%s%-16.16s | %s|\n", CURSYM(sel), buf, pname);
  1331. else if (S_ISBLK(ent->mode))
  1332. printw("%s%-16.16s b %s\n", CURSYM(sel), buf, pname);
  1333. else if (S_ISCHR(ent->mode))
  1334. printw("%s%-16.16s c %s\n", CURSYM(sel), buf, pname);
  1335. else if (ent->mode & 0100) {
  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. } else {
  1341. if (cfg.blkorder)
  1342. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1343. else
  1344. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1345. }
  1346. if (sel)
  1347. attroff(A_REVERSE);
  1348. }
  1349. static void (*printptr)(struct entry *ent, int sel, uint namecols) = &printent_long;
  1350. static char
  1351. get_fileind(mode_t mode, char *desc)
  1352. {
  1353. static char c;
  1354. if (S_ISREG(mode)) {
  1355. c = '-';
  1356. xstrlcpy(desc, "regular file", DESCRIPTOR_LEN);
  1357. if (mode & 0100)
  1358. xstrlcpy(desc + 12, ", executable", DESCRIPTOR_LEN - 12); /* Length of string "regular file" is 12 */
  1359. } else if (S_ISDIR(mode)) {
  1360. c = 'd';
  1361. xstrlcpy(desc, "directory", DESCRIPTOR_LEN);
  1362. } else if (S_ISBLK(mode)) {
  1363. c = 'b';
  1364. xstrlcpy(desc, "block special device", DESCRIPTOR_LEN);
  1365. } else if (S_ISCHR(mode)) {
  1366. c = 'c';
  1367. xstrlcpy(desc, "character special device", DESCRIPTOR_LEN);
  1368. #ifdef S_ISFIFO
  1369. } else if (S_ISFIFO(mode)) {
  1370. c = 'p';
  1371. xstrlcpy(desc, "FIFO", DESCRIPTOR_LEN);
  1372. #endif /* S_ISFIFO */
  1373. #ifdef S_ISLNK
  1374. } else if (S_ISLNK(mode)) {
  1375. c = 'l';
  1376. xstrlcpy(desc, "symbolic link", DESCRIPTOR_LEN);
  1377. #endif /* S_ISLNK */
  1378. #ifdef S_ISSOCK
  1379. } else if (S_ISSOCK(mode)) {
  1380. c = 's';
  1381. xstrlcpy(desc, "socket", DESCRIPTOR_LEN);
  1382. #endif /* S_ISSOCK */
  1383. #ifdef S_ISDOOR
  1384. /* Solaris 2.6, etc. */
  1385. } else if (S_ISDOOR(mode)) {
  1386. c = 'D';
  1387. desc[0] = '\0';
  1388. #endif /* S_ISDOOR */
  1389. } else {
  1390. /* Unknown type -- possibly a regular file? */
  1391. c = '?';
  1392. desc[0] = '\0';
  1393. }
  1394. return c;
  1395. }
  1396. /* Convert a mode field into "ls -l" type perms field. */
  1397. static char *
  1398. get_lsperms(mode_t mode, char *desc)
  1399. {
  1400. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1401. static char bits[11] = {'\0'};
  1402. bits[0] = get_fileind(mode, desc);
  1403. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  1404. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  1405. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  1406. if (mode & S_ISUID)
  1407. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1408. if (mode & S_ISGID)
  1409. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1410. if (mode & S_ISVTX)
  1411. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1412. return bits;
  1413. }
  1414. /*
  1415. * Gets only a single line (that's what we need
  1416. * for now) or shows full command output in pager.
  1417. *
  1418. * If pager is valid, returns NULL
  1419. */
  1420. static char *
  1421. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager)
  1422. {
  1423. pid_t pid;
  1424. int pipefd[2];
  1425. FILE *pf;
  1426. int tmp, flags;
  1427. char *ret = NULL;
  1428. if (pipe(pipefd) == -1)
  1429. errexit();
  1430. for (tmp = 0; tmp < 2; ++tmp) {
  1431. /* Get previous flags */
  1432. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1433. /* Set bit for non-blocking flag */
  1434. flags |= O_NONBLOCK;
  1435. /* Change flags on fd */
  1436. fcntl(pipefd[tmp], F_SETFL, flags);
  1437. }
  1438. pid = fork();
  1439. if (pid == 0) {
  1440. /* In child */
  1441. close(pipefd[0]);
  1442. dup2(pipefd[1], STDOUT_FILENO);
  1443. dup2(pipefd[1], STDERR_FILENO);
  1444. close(pipefd[1]);
  1445. execlp(file, file, arg1, arg2, NULL);
  1446. _exit(1);
  1447. }
  1448. /* In parent */
  1449. waitpid(pid, &tmp, 0);
  1450. close(pipefd[1]);
  1451. if (!pager) {
  1452. pf = fdopen(pipefd[0], "r");
  1453. if (pf) {
  1454. ret = fgets(buf, bytes, pf);
  1455. close(pipefd[0]);
  1456. }
  1457. return ret;
  1458. }
  1459. pid = fork();
  1460. if (pid == 0) {
  1461. /* Show in pager in child */
  1462. dup2(pipefd[0], STDIN_FILENO);
  1463. close(pipefd[0]);
  1464. execlp("less", "less", NULL);
  1465. _exit(1);
  1466. }
  1467. /* In parent */
  1468. waitpid(pid, &tmp, 0);
  1469. close(pipefd[0]);
  1470. return NULL;
  1471. }
  1472. static char *
  1473. xgetpwuid(uid_t uid)
  1474. {
  1475. struct passwd *pwd = getpwuid(uid);
  1476. if (!pwd)
  1477. return utils[UNKNOWN];
  1478. return pwd->pw_name;
  1479. }
  1480. static char *
  1481. xgetgrgid(gid_t gid)
  1482. {
  1483. struct group *grp = getgrgid(gid);
  1484. if (!grp)
  1485. return utils[UNKNOWN];
  1486. return grp->gr_name;
  1487. }
  1488. /*
  1489. * Follows the stat(1) output closely
  1490. */
  1491. static int
  1492. show_stats(char *fpath, char *fname, struct stat *sb)
  1493. {
  1494. char desc[DESCRIPTOR_LEN];
  1495. char *perms = get_lsperms(sb->st_mode, desc);
  1496. char *p, *begin = g_buf;
  1497. char tmp[] = "/tmp/nnnXXXXXX";
  1498. int fd = mkstemp(tmp);
  1499. if (fd == -1)
  1500. return -1;
  1501. dprintf(fd, " File: '%s'", unescape(fname, 0));
  1502. /* Show file name or 'symlink' -> 'target' */
  1503. if (perms[0] == 'l') {
  1504. /* Note that MAX_CMD_LEN > PATH_MAX */
  1505. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1506. if (len != -1) {
  1507. g_buf[len] = '\0';
  1508. /*
  1509. * We pass g_buf but unescape() operates on g_buf too!
  1510. * Read the API notes for information on how this works.
  1511. */
  1512. dprintf(fd, " -> '%s'", unescape(g_buf, 0));
  1513. }
  1514. }
  1515. /* Show size, blocks, file type */
  1516. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1517. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1518. (long long)sb->st_size, (long long)sb->st_blocks, sb->st_blksize, desc);
  1519. #else
  1520. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1521. sb->st_size, sb->st_blocks, (long)sb->st_blksize, desc);
  1522. #endif
  1523. /* Show containing device, inode, hardlink count */
  1524. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1525. snprintf(g_buf, 32, "%xh/%ud", sb->st_dev, sb->st_dev);
  1526. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1527. g_buf, (unsigned long long)sb->st_ino, sb->st_nlink);
  1528. #else
  1529. snprintf(g_buf, 32, "%lxh/%lud", (ulong)sb->st_dev, (ulong)sb->st_dev);
  1530. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1531. g_buf, sb->st_ino, (ulong)sb->st_nlink);
  1532. #endif
  1533. /* Show major, minor number for block or char device */
  1534. if (perms[0] == 'b' || perms[0] == 'c')
  1535. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1536. /* Show permissions, owner, group */
  1537. 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,
  1538. sb->st_mode & 7, perms, sb->st_uid, xgetpwuid(sb->st_uid), sb->st_gid, xgetgrgid(sb->st_gid));
  1539. /* Show last access time */
  1540. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_atime));
  1541. dprintf(fd, "\n\n Access: %s", g_buf);
  1542. /* Show last modification time */
  1543. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_mtime));
  1544. dprintf(fd, "\n Modify: %s", g_buf);
  1545. /* Show last status change time */
  1546. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_ctime));
  1547. dprintf(fd, "\n Change: %s", g_buf);
  1548. if (S_ISREG(sb->st_mode)) {
  1549. /* Show file(1) output */
  1550. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1551. if (p) {
  1552. dprintf(fd, "\n\n ");
  1553. while (*p) {
  1554. if (*p == ',') {
  1555. *p = '\0';
  1556. dprintf(fd, " %s\n", begin);
  1557. begin = p + 1;
  1558. }
  1559. ++p;
  1560. }
  1561. dprintf(fd, " %s", begin);
  1562. }
  1563. dprintf(fd, "\n\n");
  1564. } else
  1565. dprintf(fd, "\n\n\n");
  1566. close(fd);
  1567. exitcurses();
  1568. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1569. unlink(tmp);
  1570. refresh();
  1571. return 0;
  1572. }
  1573. static size_t
  1574. get_fs_info(const char *path, bool type)
  1575. {
  1576. static struct statvfs svb;
  1577. if (statvfs(path, &svb) == -1)
  1578. return 0;
  1579. if (type == CAPACITY)
  1580. return svb.f_blocks << ffs(svb.f_bsize >> 1);
  1581. else
  1582. return svb.f_bavail << ffs(svb.f_frsize >> 1);
  1583. }
  1584. static int
  1585. show_mediainfo(char *fpath, char *arg)
  1586. {
  1587. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[cfg.metaviewer], NULL, 0))
  1588. return -1;
  1589. exitcurses();
  1590. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, 1);
  1591. refresh();
  1592. return 0;
  1593. }
  1594. static int
  1595. handle_archive(char *fpath, char *arg, char *dir)
  1596. {
  1597. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[ATOOL], NULL, 0))
  1598. return -1;
  1599. if (arg[1] == 'x')
  1600. spawn(utils[ATOOL], arg, fpath, dir, F_NORMAL);
  1601. else {
  1602. exitcurses();
  1603. get_output(NULL, 0, utils[ATOOL], arg, fpath, 1);
  1604. refresh();
  1605. }
  1606. return 0;
  1607. }
  1608. /*
  1609. * The help string tokens (each line) start with a HEX value
  1610. * which indicates the number of spaces to print before the
  1611. * particular token. This method was chosen instead of a flat
  1612. * string because the number of bytes in help was increasing
  1613. * the binary size by around a hundred bytes. This would only
  1614. * have increased as we keep adding new options.
  1615. */
  1616. static int
  1617. show_help(char *path)
  1618. {
  1619. char tmp[] = "/tmp/nnnXXXXXX";
  1620. int i = 0, fd = mkstemp(tmp);
  1621. char *start, *end;
  1622. static char helpstr[] = {
  1623. "cKey | Function\n"
  1624. "e- + -\n"
  1625. "7↑, k, ^P | Prev entry\n"
  1626. "7↓, j, ^N | Next entry\n"
  1627. "7PgUp, ^U | Scroll half page up\n"
  1628. "7PgDn, ^D | Scroll half page down\n"
  1629. "1Home, g, ^, ^A | First entry\n"
  1630. "2End, G, $, ^E | Last entry\n"
  1631. "4→, ↵, l, ^M | Open file/enter dir\n"
  1632. "1←, Bksp, h, ^H | Parent dir\n"
  1633. "d^O | Open with...\n"
  1634. "5Insert, ^I | Toggle nav-as-you-type\n"
  1635. "e~ | Go HOME\n"
  1636. "e& | Start-up dir\n"
  1637. "e- | Last visited dir\n"
  1638. "e/ | Filter entries\n"
  1639. "d^/ | Open desktop search app\n"
  1640. "e. | Toggle show . files\n"
  1641. "d^B | Bookmark prompt\n"
  1642. "eb | Pin current dir\n"
  1643. "d^V | Go to pinned dir\n"
  1644. "ec | Change dir prompt\n"
  1645. "ed | Toggle detail view\n"
  1646. "eD | File details\n"
  1647. "em | Brief media info\n"
  1648. "eM | Full media info\n"
  1649. "en | Create new\n"
  1650. "d^R | Rename entry\n"
  1651. "er | Open dir in vidir\n"
  1652. "es | Toggle sort by size\n"
  1653. "aS, ^J | Toggle du mode\n"
  1654. "et | Toggle sort by mtime\n"
  1655. "a!, ^] | Spawn SHELL in dir\n"
  1656. "eR | Run custom script\n"
  1657. "ee | Edit entry in EDITOR\n"
  1658. "eo | Open DE filemanager\n"
  1659. "ep | Open entry in PAGER\n"
  1660. "ef | Archive entry\n"
  1661. "eF | List archive\n"
  1662. "d^F | Extract archive\n"
  1663. "6Space, ^K | Copy file path\n"
  1664. "d^Y | Toggle multi-copy\n"
  1665. "d^T | Toggle path quote\n"
  1666. "d^L | Redraw, clear prompt\n"
  1667. #ifdef __linux__
  1668. "eL | Lock terminal\n"
  1669. #endif
  1670. "e? | Help, settings\n"
  1671. "aQ, ^G | Quit and cd\n"
  1672. "aq, ^X | Quit\n\n"};
  1673. if (fd == -1)
  1674. return -1;
  1675. start = end = helpstr;
  1676. while (*end) {
  1677. while (*end != '\n')
  1678. ++end;
  1679. if (start == end) {
  1680. ++end;
  1681. continue;
  1682. }
  1683. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1684. start = ++end;
  1685. }
  1686. dprintf(fd, "\nVolume: %s of ", coolsize(get_fs_info(path, FREE)));
  1687. dprintf(fd, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  1688. if (getenv("NNN_BMS")) {
  1689. dprintf(fd, "BOOKMARKS\n");
  1690. for (; i < BM_MAX; ++i)
  1691. if (bookmark[i].key)
  1692. dprintf(fd, " %s: %s\n", bookmark[i].key, bookmark[i].loc);
  1693. else
  1694. break;
  1695. dprintf(fd, "\n");
  1696. }
  1697. if (editor)
  1698. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1699. if (desktop_manager)
  1700. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1701. if (idletimeout)
  1702. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1703. if (copier)
  1704. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1705. if (getenv("NNN_NO_X"))
  1706. dprintf(fd, "NNN_NO_X: %s (%s)\n", getenv("NNN_NO_X"), g_cppath);
  1707. if (getenv("NNN_SCRIPT"))
  1708. dprintf(fd, "NNN_SCRIPT: %s\n", getenv("NNN_SCRIPT"));
  1709. if (getenv("NNN_MULTISCRIPT"))
  1710. dprintf(fd, "NNN_MULTISCRIPT: %s\n", getenv("NNN_MULTISCRIPT"));
  1711. if (getenv("NNN_SHOW_HIDDEN"))
  1712. dprintf(fd, "NNN_SHOW_HIDDEN: %s\n", getenv("NNN_SHOW_HIDDEN"));
  1713. dprintf(fd, "\n");
  1714. if (getenv("PWD"))
  1715. dprintf(fd, "PWD: %s\n", getenv("PWD"));
  1716. if (getenv("SHELL"))
  1717. dprintf(fd, "SHELL: %s\n", getenv("SHELL"));
  1718. if (getenv("SHLVL"))
  1719. dprintf(fd, "SHLVL: %s\n", getenv("SHLVL"));
  1720. if (getenv("VISUAL"))
  1721. dprintf(fd, "VISUAL: %s\n", getenv("VISUAL"));
  1722. else if (getenv("EDITOR"))
  1723. dprintf(fd, "EDITOR: %s\n", getenv("EDITOR"));
  1724. if (getenv("PAGER"))
  1725. dprintf(fd, "PAGER: %s\n", getenv("PAGER"));
  1726. dprintf(fd, "\nVersion: %s\n%s\n", VERSION, GENERAL_INFO);
  1727. close(fd);
  1728. exitcurses();
  1729. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1730. unlink(tmp);
  1731. refresh();
  1732. return 0;
  1733. }
  1734. static int
  1735. sum_bsizes(const char *fpath, const struct stat *sb,
  1736. int typeflag, struct FTW *ftwbuf)
  1737. {
  1738. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1739. ent_blocks += sb->st_blocks;
  1740. ++num_files;
  1741. return 0;
  1742. }
  1743. static int
  1744. dentfill(char *path, struct entry **dents,
  1745. int (*filter)(regex_t *, char *), regex_t *re)
  1746. {
  1747. static DIR *dirp;
  1748. static struct dirent *dp;
  1749. static char *namep, *pnb;
  1750. static struct entry *dentp;
  1751. static size_t off, namebuflen = NAMEBUF_INCR;
  1752. static ulong num_saved;
  1753. static int fd, n, count;
  1754. static struct stat sb_path, sb;
  1755. off = 0;
  1756. dirp = opendir(path);
  1757. if (dirp == NULL)
  1758. return 0;
  1759. fd = dirfd(dirp);
  1760. n = 0;
  1761. if (cfg.blkorder) {
  1762. num_files = 0;
  1763. dir_blocks = 0;
  1764. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  1765. printwarn();
  1766. return 0;
  1767. }
  1768. }
  1769. while ((dp = readdir(dirp)) != NULL) {
  1770. namep = dp->d_name;
  1771. if (filter(re, namep) == 0) {
  1772. if (!cfg.blkorder)
  1773. continue;
  1774. /* Skip self and parent */
  1775. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  1776. continue;
  1777. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  1778. continue;
  1779. if (S_ISDIR(sb.st_mode)) {
  1780. if (sb_path.st_dev == sb.st_dev) {
  1781. ent_blocks = 0;
  1782. mkpath(path, namep, g_buf, PATH_MAX);
  1783. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1784. printmsg(messages[STR_NFTWFAIL_ID]);
  1785. dir_blocks += sb.st_blocks;
  1786. } else
  1787. dir_blocks += ent_blocks;
  1788. }
  1789. } else {
  1790. if (sb.st_blocks)
  1791. dir_blocks += sb.st_blocks;
  1792. ++num_files;
  1793. }
  1794. continue;
  1795. }
  1796. /* Skip self and parent */
  1797. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1798. (namep[1] == '.' && namep[2] == '\0'))))
  1799. continue;
  1800. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1801. DPRINTF_S(namep);
  1802. continue;
  1803. }
  1804. if (n == total_dents) {
  1805. total_dents += ENTRY_INCR;
  1806. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  1807. if (*dents == NULL) {
  1808. if (pnamebuf)
  1809. free(pnamebuf);
  1810. errexit();
  1811. }
  1812. DPRINTF_P(*dents);
  1813. }
  1814. /* If there's not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  1815. if (namebuflen - off < NAME_MAX + 1) {
  1816. namebuflen += NAMEBUF_INCR;
  1817. pnb = pnamebuf;
  1818. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  1819. if (pnamebuf == NULL) {
  1820. free(*dents);
  1821. errexit();
  1822. }
  1823. DPRINTF_P(pnamebuf);
  1824. /* realloc() may result in memory move, we must re-adjust if that happens */
  1825. if (pnb != pnamebuf) {
  1826. dentp = *dents;
  1827. dentp->name = pnamebuf;
  1828. for (count = 1; count < n; ++dentp, ++count)
  1829. /* Current filename starts at last filename start + length */
  1830. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  1831. }
  1832. }
  1833. dentp = *dents + n;
  1834. /* Copy file name */
  1835. dentp->name = (char *)((size_t)pnamebuf + off);
  1836. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  1837. off += dentp->nlen;
  1838. /* Copy other fields */
  1839. dentp->mode = sb.st_mode;
  1840. dentp->t = sb.st_mtime;
  1841. dentp->size = sb.st_size;
  1842. if (cfg.blkorder) {
  1843. if (S_ISDIR(sb.st_mode)) {
  1844. ent_blocks = 0;
  1845. num_saved = num_files + 1;
  1846. mkpath(path, namep, g_buf, PATH_MAX);
  1847. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1848. printmsg(messages[STR_NFTWFAIL_ID]);
  1849. dentp->blocks = sb.st_blocks;
  1850. } else
  1851. dentp->blocks = ent_blocks;
  1852. if (sb_path.st_dev == sb.st_dev)
  1853. dir_blocks += dentp->blocks;
  1854. else
  1855. num_files = num_saved;
  1856. } else {
  1857. dentp->blocks = sb.st_blocks;
  1858. dir_blocks += dentp->blocks;
  1859. ++num_files;
  1860. }
  1861. }
  1862. ++n;
  1863. }
  1864. /* Should never be null */
  1865. if (closedir(dirp) == -1) {
  1866. if (*dents) {
  1867. free(pnamebuf);
  1868. free(*dents);
  1869. }
  1870. errexit();
  1871. }
  1872. return n;
  1873. }
  1874. static void
  1875. dentfree(struct entry *dents)
  1876. {
  1877. free(pnamebuf);
  1878. free(dents);
  1879. }
  1880. /* Return the position of the matching entry or 0 otherwise */
  1881. static int
  1882. dentfind(struct entry *dents, const char *fname, int n)
  1883. {
  1884. static int i;
  1885. if (!fname)
  1886. return 0;
  1887. DPRINTF_S(fname);
  1888. for (i = 0; i < n; ++i)
  1889. if (strcmp(fname, dents[i].name) == 0)
  1890. return i;
  1891. return 0;
  1892. }
  1893. static int
  1894. populate(char *path, char *oldname, char *fltr)
  1895. {
  1896. static regex_t re;
  1897. /* Can fail when permissions change while browsing.
  1898. * It's assumed that path IS a directory when we are here.
  1899. */
  1900. if (access(path, R_OK) == -1)
  1901. return -1;
  1902. /* Search filter */
  1903. if (setfilter(&re, fltr) != 0)
  1904. return -1;
  1905. if (cfg.blkorder) {
  1906. printmsg("calculating...");
  1907. refresh();
  1908. }
  1909. #ifdef DEBUGMODE
  1910. struct timespec ts1, ts2;
  1911. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  1912. #endif
  1913. ndents = dentfill(path, &dents, visible, &re);
  1914. regfree(&re);
  1915. if (ndents == 0)
  1916. return 0;
  1917. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1918. #ifdef DEBUGMODE
  1919. clock_gettime(CLOCK_REALTIME, &ts2);
  1920. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  1921. #endif
  1922. /* Find cur from history */
  1923. cur = dentfind(dents, oldname, ndents);
  1924. return 0;
  1925. }
  1926. static void
  1927. redraw(char *path)
  1928. {
  1929. static char buf[NAME_MAX + 65] __attribute__ ((aligned));
  1930. static size_t ncols;
  1931. static int nlines, i;
  1932. static bool mode_changed;
  1933. mode_changed = FALSE;
  1934. nlines = MIN(LINES - 4, ndents);
  1935. /* Clean screen */
  1936. erase();
  1937. if (cfg.copymode)
  1938. if (g_crc != crc8fast((uchar *)dents, ndents * sizeof(struct entry))) {
  1939. cfg.copymode = 0;
  1940. DPRINTF_S("copymode off");
  1941. }
  1942. /* Fail redraw if < than 10 columns */
  1943. if (COLS < 10) {
  1944. printmsg("too few columns!");
  1945. return;
  1946. }
  1947. /* Strip trailing slashes */
  1948. for (i = strlen(path) - 1; i > 0; --i)
  1949. if (path[i] == '/')
  1950. path[i] = '\0';
  1951. else
  1952. break;
  1953. DPRINTF_D(cur);
  1954. DPRINTF_S(path);
  1955. if (!realpath(path, g_buf)) {
  1956. printwarn();
  1957. return;
  1958. }
  1959. ncols = COLS;
  1960. if (ncols > PATH_MAX)
  1961. ncols = PATH_MAX;
  1962. /* No text wrapping in cwd line */
  1963. /* Show CWD: - strlen(CWD) - 1 = 6 */
  1964. g_buf[ncols - 6] = '\0';
  1965. printw(CWD "%s\n\n", g_buf);
  1966. /* Fallback to light mode if less than 35 columns */
  1967. if (ncols < 35 && cfg.showdetail) {
  1968. cfg.showdetail ^= 1;
  1969. printptr = &printent;
  1970. mode_changed = TRUE;
  1971. }
  1972. /* Calculate the number of cols available to print entry name */
  1973. if (cfg.showdetail)
  1974. ncols -= 32;
  1975. else
  1976. ncols -= 5;
  1977. if (cfg.showcolor) {
  1978. attron(COLOR_PAIR(1) | A_BOLD);
  1979. cfg.dircolor = 1;
  1980. }
  1981. /* Print listing */
  1982. if (cur < (nlines >> 1)) {
  1983. for (i = 0; i < nlines; ++i)
  1984. printptr(&dents[i], i == cur, ncols);
  1985. } else if (cur >= ndents - (nlines >> 1)) {
  1986. for (i = ndents - nlines; i < ndents; ++i)
  1987. printptr(&dents[i], i == cur, ncols);
  1988. } else {
  1989. static int odd;
  1990. odd = ISODD(nlines);
  1991. nlines >>= 1;
  1992. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1993. printptr(&dents[i], i == cur, ncols);
  1994. }
  1995. /* Must reset e.g. no files in dir */
  1996. if (cfg.dircolor) {
  1997. attroff(COLOR_PAIR(1) | A_BOLD);
  1998. cfg.dircolor = 0;
  1999. }
  2000. if (cfg.showdetail) {
  2001. if (ndents) {
  2002. static char sort[9];
  2003. if (cfg.mtimeorder)
  2004. xstrlcpy(sort, "by time ", 9);
  2005. else if (cfg.sizeorder)
  2006. xstrlcpy(sort, "by size ", 9);
  2007. else
  2008. sort[0] = '\0';
  2009. /* We need to show filename as it may be truncated in directory listing */
  2010. if (!cfg.blkorder)
  2011. snprintf(buf, NAME_MAX + 65, "%d/%d %s[%s%s]",
  2012. cur + 1, ndents, sort, unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  2013. else {
  2014. i = snprintf(buf, 64, "%d/%d du: %s (%lu files) ", cur + 1, ndents, coolsize(dir_blocks << 9), num_files);
  2015. snprintf(buf + i, NAME_MAX, "vol: %s free [%s%s]",
  2016. coolsize(get_fs_info(path, FREE)), unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  2017. }
  2018. printmsg(buf);
  2019. } else
  2020. printmsg("0 items");
  2021. }
  2022. if (mode_changed) {
  2023. cfg.showdetail ^= 1;
  2024. printptr = &printent_long;
  2025. }
  2026. }
  2027. static void
  2028. browse(char *ipath, char *ifilter)
  2029. {
  2030. static char path[PATH_MAX] __attribute__ ((aligned));
  2031. static char newpath[PATH_MAX] __attribute__ ((aligned));
  2032. static char lastdir[PATH_MAX] __attribute__ ((aligned));
  2033. static char mark[PATH_MAX] __attribute__ ((aligned));
  2034. static char fltr[NAME_MAX + 1] __attribute__ ((aligned));
  2035. static char oldname[NAME_MAX + 1] __attribute__ ((aligned));
  2036. char *dir, *tmp, *run = NULL, *env = NULL;
  2037. struct stat sb;
  2038. int r, fd, presel, ncp = 0, copystartid = 0, copyendid = 0;
  2039. enum action sel = SEL_RUNARG + 1;
  2040. bool dir_changed = FALSE;
  2041. xstrlcpy(path, ipath, PATH_MAX);
  2042. copyfilter();
  2043. oldname[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  2044. if (cfg.filtermode)
  2045. presel = FILTER;
  2046. else
  2047. presel = 0;
  2048. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  2049. if (dents == NULL)
  2050. errexit();
  2051. DPRINTF_P(dents);
  2052. /* Allocate buffer to hold names */
  2053. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  2054. if (pnamebuf == NULL) {
  2055. free(dents);
  2056. errexit();
  2057. }
  2058. DPRINTF_P(pnamebuf);
  2059. begin:
  2060. #ifdef LINUX_INOTIFY
  2061. if (dir_changed && inotify_wd >= 0) {
  2062. inotify_rm_watch(inotify_fd, inotify_wd);
  2063. inotify_wd = -1;
  2064. dir_changed = FALSE;
  2065. }
  2066. #elif defined(BSD_KQUEUE)
  2067. if (dir_changed && event_fd >= 0) {
  2068. close(event_fd);
  2069. event_fd = -1;
  2070. dir_changed = FALSE;
  2071. }
  2072. #endif
  2073. if (populate(path, oldname, fltr) == -1) {
  2074. printwarn();
  2075. goto nochange;
  2076. }
  2077. #ifdef LINUX_INOTIFY
  2078. if (inotify_wd == -1)
  2079. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  2080. #elif defined(BSD_KQUEUE)
  2081. if (event_fd == -1) {
  2082. #if defined(O_EVTONLY)
  2083. event_fd = open(path, O_EVTONLY);
  2084. #else
  2085. event_fd = open(path, O_RDONLY);
  2086. #endif
  2087. if (event_fd >= 0)
  2088. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  2089. }
  2090. #endif
  2091. for (;;) {
  2092. redraw(path);
  2093. nochange:
  2094. /* Exit if parent has exited */
  2095. if (getppid() == 1)
  2096. _exit(0);
  2097. sel = nextsel(&run, &env, &presel);
  2098. switch (sel) {
  2099. case SEL_BACK:
  2100. /* There is no going back */
  2101. if (istopdir(path)) {
  2102. /* Continue in navigate-as-you-type mode, if enabled */
  2103. if (cfg.filtermode)
  2104. presel = FILTER;
  2105. goto nochange;
  2106. }
  2107. dir = xdirname(path);
  2108. if (access(dir, R_OK) == -1) {
  2109. printwarn();
  2110. goto nochange;
  2111. }
  2112. /* Save history */
  2113. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2114. /* Save last working directory */
  2115. xstrlcpy(lastdir, path, PATH_MAX);
  2116. dir_changed = TRUE;
  2117. xstrlcpy(path, dir, PATH_MAX);
  2118. /* Reset filter */
  2119. copyfilter();
  2120. if (cfg.filtermode)
  2121. presel = FILTER;
  2122. goto begin;
  2123. case SEL_GOIN:
  2124. /* Cannot descend in empty directories */
  2125. if (ndents == 0)
  2126. goto begin;
  2127. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2128. DPRINTF_S(newpath);
  2129. /* Get path info */
  2130. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  2131. if (fd == -1) {
  2132. printwarn();
  2133. goto nochange;
  2134. }
  2135. if (fstat(fd, &sb) == -1) {
  2136. printwarn();
  2137. close(fd);
  2138. goto nochange;
  2139. }
  2140. close(fd);
  2141. DPRINTF_U(sb.st_mode);
  2142. switch (sb.st_mode & S_IFMT) {
  2143. case S_IFDIR:
  2144. if (access(newpath, R_OK) == -1) {
  2145. printwarn();
  2146. goto nochange;
  2147. }
  2148. /* Save last working directory */
  2149. xstrlcpy(lastdir, path, PATH_MAX);
  2150. dir_changed = TRUE;
  2151. xstrlcpy(path, newpath, PATH_MAX);
  2152. oldname[0] = '\0';
  2153. /* Reset filter */
  2154. copyfilter();
  2155. if (cfg.filtermode)
  2156. presel = FILTER;
  2157. goto begin;
  2158. case S_IFREG:
  2159. {
  2160. /* If NNN_USE_EDITOR is set,
  2161. * open text in EDITOR
  2162. */
  2163. if (editor) {
  2164. if (getmime(dents[cur].name)) {
  2165. spawn(editor, newpath, NULL, path, F_NORMAL);
  2166. continue;
  2167. }
  2168. /* Recognize and open plain
  2169. * text files with vi
  2170. */
  2171. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  2172. continue;
  2173. if (strstr(g_buf, "text/") == g_buf) {
  2174. spawn(editor, newpath, NULL, path, F_NORMAL);
  2175. continue;
  2176. }
  2177. }
  2178. /* Invoke desktop opener as last resort */
  2179. spawn(utils[OPENER], newpath, NULL, NULL, F_NOWAIT | F_NOTRACE);
  2180. continue;
  2181. }
  2182. default:
  2183. printmsg("unsupported file");
  2184. goto nochange;
  2185. }
  2186. case SEL_NEXT:
  2187. if (cur < ndents - 1)
  2188. ++cur;
  2189. else if (ndents)
  2190. /* Roll over, set cursor to first entry */
  2191. cur = 0;
  2192. break;
  2193. case SEL_PREV:
  2194. if (cur > 0)
  2195. --cur;
  2196. else if (ndents)
  2197. /* Roll over, set cursor to last entry */
  2198. cur = ndents - 1;
  2199. break;
  2200. case SEL_PGDN:
  2201. if (cur < ndents - 1)
  2202. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  2203. break;
  2204. case SEL_PGUP:
  2205. if (cur > 0)
  2206. cur -= MIN((LINES - 4) / 2, cur);
  2207. break;
  2208. case SEL_HOME:
  2209. cur = 0;
  2210. break;
  2211. case SEL_END:
  2212. cur = ndents - 1;
  2213. break;
  2214. case SEL_CD:
  2215. {
  2216. char *input;
  2217. int truecd;
  2218. /* Save the program start dir */
  2219. tmp = getcwd(newpath, PATH_MAX);
  2220. if (tmp == NULL) {
  2221. printwarn();
  2222. goto nochange;
  2223. }
  2224. /* Switch to current path for readline(3) */
  2225. if (chdir(path) == -1) {
  2226. printwarn();
  2227. goto nochange;
  2228. }
  2229. exitcurses();
  2230. tmp = readline("cd: ");
  2231. refresh();
  2232. /* Change back to program start dir */
  2233. if (chdir(newpath) == -1)
  2234. printwarn();
  2235. if (tmp[0] == '\0')
  2236. break;
  2237. /* Add to readline(3) history */
  2238. add_history(tmp);
  2239. input = tmp;
  2240. tmp = strstrip(tmp);
  2241. if (tmp[0] == '\0') {
  2242. free(input);
  2243. break;
  2244. }
  2245. truecd = 0;
  2246. if (tmp[0] == '~') {
  2247. /* Expand ~ to HOME absolute path */
  2248. char *home = getenv("HOME");
  2249. if (home)
  2250. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  2251. else {
  2252. free(input);
  2253. printmsg(messages[STR_NOHOME_ID]);
  2254. goto nochange;
  2255. }
  2256. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  2257. if (lastdir[0] == '\0') {
  2258. free(input);
  2259. break;
  2260. }
  2261. /* Switch to last visited dir */
  2262. xstrlcpy(newpath, lastdir, PATH_MAX);
  2263. truecd = 1;
  2264. } else if ((r = all_dots(tmp))) {
  2265. if (r == 1) {
  2266. /* Always in the current dir */
  2267. free(input);
  2268. break;
  2269. }
  2270. /* Show a message if already at / */
  2271. if (istopdir(path)) {
  2272. free(input);
  2273. /* Continue in navigate-as-you-type mode, if enabled */
  2274. if (cfg.filtermode)
  2275. presel = FILTER;
  2276. goto nochange;
  2277. }
  2278. --r; /* One . for the current dir */
  2279. dir = path;
  2280. /* Note: fd is used as a tmp variable here */
  2281. for (fd = 0; fd < r; ++fd) {
  2282. /* Reached / ? */
  2283. if (istopdir(path)) {
  2284. /* Can't cd beyond / */
  2285. break;
  2286. }
  2287. dir = xdirname(dir);
  2288. if (access(dir, R_OK) == -1) {
  2289. printwarn();
  2290. free(input);
  2291. goto nochange;
  2292. }
  2293. }
  2294. truecd = 1;
  2295. /* Save the path in case of cd ..
  2296. * We mark the current dir in parent dir
  2297. */
  2298. if (r == 1) {
  2299. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2300. truecd = 2;
  2301. }
  2302. xstrlcpy(newpath, dir, PATH_MAX);
  2303. } else
  2304. mkpath(path, tmp, newpath, PATH_MAX);
  2305. free(input);
  2306. if (!xdiraccess(newpath))
  2307. goto nochange;
  2308. if (truecd == 0) {
  2309. /* Probable change in dir */
  2310. /* No-op if it's the same directory */
  2311. if (strcmp(path, newpath) == 0)
  2312. break;
  2313. oldname[0] = '\0';
  2314. } else if (truecd == 1)
  2315. /* Sure change in dir */
  2316. oldname[0] = '\0';
  2317. /* Save last working directory */
  2318. xstrlcpy(lastdir, path, PATH_MAX);
  2319. dir_changed = TRUE;
  2320. /* Save the newly opted dir in path */
  2321. xstrlcpy(path, newpath, PATH_MAX);
  2322. /* Reset filter */
  2323. copyfilter();
  2324. DPRINTF_S(path);
  2325. if (cfg.filtermode)
  2326. presel = FILTER;
  2327. goto begin;
  2328. }
  2329. case SEL_CDHOME:
  2330. dir = getenv("HOME");
  2331. if (dir == NULL) {
  2332. clearprompt();
  2333. goto nochange;
  2334. } // fallthrough
  2335. case SEL_CDBEGIN:
  2336. if (sel == SEL_CDBEGIN)
  2337. dir = ipath;
  2338. if (!xdiraccess(dir)) {
  2339. goto nochange;
  2340. }
  2341. if (strcmp(path, dir) == 0) {
  2342. break;
  2343. }
  2344. /* Save last working directory */
  2345. xstrlcpy(lastdir, path, PATH_MAX);
  2346. dir_changed = TRUE;
  2347. xstrlcpy(path, dir, PATH_MAX);
  2348. oldname[0] = '\0';
  2349. /* Reset filter */
  2350. copyfilter();
  2351. DPRINTF_S(path);
  2352. if (cfg.filtermode)
  2353. presel = FILTER;
  2354. goto begin;
  2355. case SEL_CDLAST: // fallthrough
  2356. case SEL_VISIT:
  2357. if (sel == SEL_VISIT) {
  2358. if (strcmp(mark, path) == 0)
  2359. break;
  2360. tmp = mark;
  2361. } else
  2362. tmp = lastdir;
  2363. if (tmp[0] == '\0') {
  2364. printmsg("not set...");
  2365. goto nochange;
  2366. }
  2367. if (!xdiraccess(tmp))
  2368. goto nochange;
  2369. xstrlcpy(newpath, tmp, PATH_MAX);
  2370. xstrlcpy(lastdir, path, PATH_MAX);
  2371. dir_changed = TRUE;
  2372. xstrlcpy(path, newpath, PATH_MAX);
  2373. oldname[0] = '\0';
  2374. /* Reset filter */
  2375. copyfilter();
  2376. DPRINTF_S(path);
  2377. if (cfg.filtermode)
  2378. presel = FILTER;
  2379. goto begin;
  2380. case SEL_CDBM:
  2381. tmp = xreadline(NULL, "key: ");
  2382. if (tmp == NULL || tmp[0] == '\0')
  2383. break;
  2384. /* Interpret ~, - and & keys */
  2385. if ((tmp[1] == '\0') && (tmp[0] == '~' || tmp[0] == '-' || tmp[0] == '&')) {
  2386. presel = tmp[0];
  2387. goto begin;
  2388. }
  2389. if (get_bm_loc(tmp, newpath) == NULL) {
  2390. printmsg(messages[STR_INVBM_ID]);
  2391. goto nochange;
  2392. }
  2393. if (!xdiraccess(newpath))
  2394. goto nochange;
  2395. if (strcmp(path, newpath) == 0)
  2396. break;
  2397. oldname[0] = '\0';
  2398. /* Save last working directory */
  2399. xstrlcpy(lastdir, path, PATH_MAX);
  2400. dir_changed = TRUE;
  2401. /* Save the newly opted dir in path */
  2402. xstrlcpy(path, newpath, PATH_MAX);
  2403. /* Reset filter */
  2404. copyfilter();
  2405. DPRINTF_S(path);
  2406. if (cfg.filtermode)
  2407. presel = FILTER;
  2408. goto begin;
  2409. case SEL_PIN:
  2410. xstrlcpy(mark, path, PATH_MAX);
  2411. printmsg(mark);
  2412. goto nochange;
  2413. case SEL_FLTR:
  2414. presel = filterentries(path);
  2415. copyfilter();
  2416. DPRINTF_S(fltr);
  2417. /* Save current */
  2418. if (ndents > 0)
  2419. copycurname();
  2420. goto nochange;
  2421. case SEL_MFLTR:
  2422. cfg.filtermode ^= 1;
  2423. if (cfg.filtermode)
  2424. presel = FILTER;
  2425. else {
  2426. /* Save current */
  2427. if (ndents > 0)
  2428. copycurname();
  2429. /* Start watching the directory */
  2430. goto begin;
  2431. }
  2432. goto nochange;
  2433. case SEL_SEARCH:
  2434. spawn(player, path, "search", NULL, F_NORMAL);
  2435. break;
  2436. case SEL_TOGGLEDOT:
  2437. cfg.showhidden ^= 1;
  2438. initfilter(cfg.showhidden, &ifilter);
  2439. copyfilter();
  2440. goto begin;
  2441. case SEL_DETAIL:
  2442. cfg.showdetail ^= 1;
  2443. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2444. /* Save current */
  2445. if (ndents > 0)
  2446. copycurname();
  2447. goto begin;
  2448. case SEL_STATS:
  2449. if (ndents > 0) {
  2450. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2451. if (lstat(newpath, &sb) == -1) {
  2452. if (dents)
  2453. dentfree(dents);
  2454. errexit();
  2455. } else {
  2456. if (show_stats(newpath, dents[cur].name, &sb) < 0) {
  2457. printwarn();
  2458. goto nochange;
  2459. }
  2460. }
  2461. }
  2462. break;
  2463. case SEL_LIST: // fallthrough
  2464. case SEL_EXTRACT: // fallthrough
  2465. case SEL_MEDIA: // fallthrough
  2466. case SEL_FMEDIA:
  2467. if (ndents > 0) {
  2468. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2469. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2470. r = show_mediainfo(newpath, run);
  2471. else
  2472. r = handle_archive(newpath, run, path);
  2473. if (r == -1) {
  2474. xstrlcpy(newpath, "missing ", PATH_MAX);
  2475. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2476. xstrlcpy(newpath + 8, utils[cfg.metaviewer], 32);
  2477. else
  2478. xstrlcpy(newpath + 8, utils[ATOOL], 32);
  2479. printmsg(newpath);
  2480. goto nochange;
  2481. }
  2482. /* In case of successful archive extract, reload contents */
  2483. if (sel == SEL_EXTRACT) {
  2484. /* Continue in navigate-as-you-type mode, if enabled */
  2485. if (cfg.filtermode)
  2486. presel = FILTER;
  2487. /* Save current */
  2488. copycurname();
  2489. /* Repopulate as directory content may have changed */
  2490. goto begin;
  2491. }
  2492. }
  2493. break;
  2494. case SEL_DFB:
  2495. if (!desktop_manager) {
  2496. printmsg("set NNN_DE_FILE_MANAGER");
  2497. goto nochange;
  2498. }
  2499. spawn(desktop_manager, path, NULL, path, F_NOWAIT | F_NOTRACE);
  2500. break;
  2501. case SEL_FSIZE:
  2502. cfg.sizeorder ^= 1;
  2503. cfg.mtimeorder = 0;
  2504. cfg.blkorder = 0;
  2505. cfg.copymode = 0;
  2506. /* Save current */
  2507. if (ndents > 0)
  2508. copycurname();
  2509. goto begin;
  2510. case SEL_BSIZE:
  2511. cfg.blkorder ^= 1;
  2512. if (cfg.blkorder) {
  2513. cfg.showdetail = 1;
  2514. printptr = &printent_long;
  2515. }
  2516. cfg.mtimeorder = 0;
  2517. cfg.sizeorder = 0;
  2518. cfg.copymode = 0;
  2519. /* Save current */
  2520. if (ndents > 0)
  2521. copycurname();
  2522. goto begin;
  2523. case SEL_MTIME:
  2524. cfg.mtimeorder ^= 1;
  2525. cfg.sizeorder = 0;
  2526. cfg.blkorder = 0;
  2527. cfg.copymode = 0;
  2528. /* Save current */
  2529. if (ndents > 0)
  2530. copycurname();
  2531. goto begin;
  2532. case SEL_REDRAW:
  2533. /* Save current */
  2534. if (ndents > 0)
  2535. copycurname();
  2536. goto begin;
  2537. case SEL_COPY:
  2538. if (!(cfg.noxdisplay || copier))
  2539. printmsg(messages[STR_COPY_ID]);
  2540. else if (ndents) {
  2541. if (cfg.copymode) {
  2542. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2543. if (!appendfpath(newpath, r))
  2544. goto nochange;
  2545. ++ncp;
  2546. printmsg(newpath);
  2547. } else if (cfg.quote) {
  2548. g_buf[0] = '\'';
  2549. r = mkpath(path, dents[cur].name, g_buf + 1, PATH_MAX);
  2550. g_buf[r] = '\'';
  2551. g_buf[r + 1] = '\0';
  2552. if (cfg.noxdisplay)
  2553. writecp(g_buf, r + 1); /* Truncate NULL from end */
  2554. else
  2555. spawn(copier, g_buf, NULL, NULL, F_NOTRACE);
  2556. g_buf[r] = '\0';
  2557. printmsg(g_buf + 1);
  2558. } else {
  2559. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2560. if (cfg.noxdisplay)
  2561. writecp(newpath, r - 1); /* Truncate NULL from end */
  2562. else
  2563. spawn(copier, newpath, NULL, NULL, F_NOTRACE);
  2564. printmsg(newpath);
  2565. }
  2566. }
  2567. goto nochange;
  2568. case SEL_COPYMUL:
  2569. if (!(cfg.noxdisplay || copier))
  2570. printmsg(messages[STR_COPY_ID]);
  2571. else if (ndents) {
  2572. cfg.copymode ^= 1;
  2573. if (cfg.copymode) {
  2574. g_crc = crc8fast((uchar *)dents, ndents * sizeof(struct entry));
  2575. copystartid = cur;
  2576. copybufpos = 0;
  2577. ncp = 0;
  2578. printmsg("multi-copy on");
  2579. DPRINTF_S("copymode on");
  2580. } else {
  2581. if (!ncp) { /* Handle range selection */
  2582. if (cur < copystartid) {
  2583. copyendid = copystartid;
  2584. copystartid = cur;
  2585. } else
  2586. copyendid = cur;
  2587. if (copystartid < copyendid) {
  2588. for (r = copystartid; r <= copyendid; ++r)
  2589. if (!appendfpath(newpath, mkpath(path, dents[r].name, newpath, PATH_MAX)))
  2590. goto nochange;
  2591. snprintf(newpath, PATH_MAX, "%d files copied", copyendid - copystartid + 1);
  2592. printmsg(newpath);
  2593. }
  2594. }
  2595. if (copybufpos) { /* File path(s) written to the buffer */
  2596. if (cfg.noxdisplay)
  2597. writecp(pcopybuf, copybufpos - 1); /* Truncate NULL from end */
  2598. else
  2599. spawn(copier, pcopybuf, NULL, NULL, F_NOTRACE);
  2600. if (ncp) /* Some files cherry picked */
  2601. {
  2602. snprintf(newpath, PATH_MAX, "%d files copied", ncp);
  2603. printmsg(newpath);
  2604. }
  2605. } else
  2606. printmsg("multi-copy off");
  2607. }
  2608. }
  2609. goto nochange;
  2610. case SEL_QUOTE:
  2611. cfg.quote ^= 1;
  2612. DPRINTF_D(cfg.quote);
  2613. if (cfg.quote)
  2614. printmsg("quotes on");
  2615. else
  2616. printmsg("quotes off");
  2617. goto nochange;
  2618. case SEL_OPEN: // fallthrough
  2619. case SEL_ARCHIVE: // fallthrough
  2620. case SEL_NEW:
  2621. if (sel == SEL_OPEN)
  2622. tmp = xreadline(NULL, "open with: ");
  2623. else
  2624. tmp = xreadline(NULL, "name: ");
  2625. if (tmp == NULL || tmp[0] == '\0')
  2626. break;
  2627. /* Allow only relative, same dir paths */
  2628. if (tmp[0] == '/' || strcmp(xbasename(tmp), tmp) != 0) {
  2629. printmsg(messages[STR_INPUT_ID]);
  2630. goto nochange;
  2631. }
  2632. if (sel == SEL_OPEN) {
  2633. printprompt("press 'c' for cli mode");
  2634. cleartimeout();
  2635. r = getch();
  2636. settimeout();
  2637. if (r == 'c')
  2638. r = F_NORMAL;
  2639. else
  2640. r = F_NOWAIT | F_NOTRACE;
  2641. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2642. spawn(tmp, newpath, NULL, path, r);
  2643. continue;
  2644. } else if (sel == SEL_ARCHIVE) {
  2645. /* newpath is used as temporary buffer */
  2646. if (!get_output(newpath, PATH_MAX, "which", utils[APACK], NULL, 0)) {
  2647. printmsg("apack missing");
  2648. continue;
  2649. }
  2650. spawn(utils[APACK], tmp, dents[cur].name, path, F_NORMAL);
  2651. /* Continue in navigate-as-you-type mode, if enabled */
  2652. if (cfg.filtermode)
  2653. presel = FILTER;
  2654. /* Save current */
  2655. copycurname();
  2656. /* Repopulate as directory content may have changed */
  2657. goto begin;
  2658. }
  2659. /* Open the descriptor to currently open directory */
  2660. fd = open(path, O_RDONLY | O_DIRECTORY);
  2661. if (fd == -1) {
  2662. printwarn();
  2663. goto nochange;
  2664. }
  2665. /* Check if another file with same name exists */
  2666. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2667. printmsg("entry exists");
  2668. goto nochange;
  2669. }
  2670. /* Check if it's a dir or file */
  2671. printprompt("press 'f'(ile) or 'd'(ir)");
  2672. cleartimeout();
  2673. r = getch();
  2674. settimeout();
  2675. if (r == 'f') {
  2676. r = openat(fd, tmp, O_CREAT, 0666);
  2677. close(r);
  2678. } else if (r == 'd')
  2679. r = mkdirat(fd, tmp, 0777);
  2680. else {
  2681. close(fd);
  2682. break;
  2683. }
  2684. if (r == -1) {
  2685. printwarn();
  2686. close(fd);
  2687. goto nochange;
  2688. }
  2689. close(fd);
  2690. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2691. goto begin;
  2692. case SEL_RENAME:
  2693. if (ndents <= 0)
  2694. break;
  2695. tmp = xreadline(dents[cur].name, "");
  2696. if (tmp == NULL || tmp[0] == '\0')
  2697. break;
  2698. /* Allow only relative, same dir paths */
  2699. if (tmp[0] == '/' || strcmp(xbasename(tmp), tmp) != 0) {
  2700. printmsg(messages[STR_INPUT_ID]);
  2701. goto nochange;
  2702. }
  2703. /* Skip renaming to same name */
  2704. if (strcmp(tmp, dents[cur].name) == 0)
  2705. break;
  2706. /* Open the descriptor to currently open directory */
  2707. fd = open(path, O_RDONLY | O_DIRECTORY);
  2708. if (fd == -1) {
  2709. printwarn();
  2710. goto nochange;
  2711. }
  2712. /* Check if another file with same name exists */
  2713. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2714. /* File with the same name exists */
  2715. printprompt("press 'y' to overwrite");
  2716. cleartimeout();
  2717. r = getch();
  2718. settimeout();
  2719. if (r != 'y') {
  2720. close(fd);
  2721. break;
  2722. }
  2723. }
  2724. /* Rename the file */
  2725. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  2726. printwarn();
  2727. close(fd);
  2728. goto nochange;
  2729. }
  2730. close(fd);
  2731. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2732. goto begin;
  2733. case SEL_RENAMEALL:
  2734. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[VIDIR], NULL, 0)) {
  2735. printmsg("vidir missing");
  2736. goto nochange;
  2737. }
  2738. spawn(utils[VIDIR], ".", NULL, path, F_NORMAL);
  2739. /* Save current */
  2740. if (ndents > 0)
  2741. copycurname();
  2742. goto begin;
  2743. case SEL_HELP:
  2744. show_help(path);
  2745. /* Continue in navigate-as-you-type mode, if enabled */
  2746. if (cfg.filtermode)
  2747. presel = FILTER;
  2748. break;
  2749. case SEL_RUN: // fallthrough
  2750. case SEL_RUNSCRIPT:
  2751. run = xgetenv(env, run);
  2752. if (sel == SEL_RUNSCRIPT) {
  2753. tmp = getenv("NNN_SCRIPT");
  2754. if (tmp) {
  2755. if (getenv("NNN_MULTISCRIPT")) {
  2756. size_t _len = xstrlcpy(newpath, tmp, PATH_MAX);
  2757. tmp = xreadline(NULL, "script suffix: ");
  2758. if (tmp && tmp[0])
  2759. xstrlcpy(newpath + _len - 1, tmp, PATH_MAX - _len);
  2760. tmp = newpath;
  2761. }
  2762. spawn(run, tmp, NULL, path, F_NORMAL | F_SIGINT);
  2763. }
  2764. } else {
  2765. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2766. /* Continue in navigate-as-you-type mode, if enabled */
  2767. if (cfg.filtermode)
  2768. presel = FILTER;
  2769. }
  2770. /* Save current */
  2771. if (ndents > 0)
  2772. copycurname();
  2773. /* Repopulate as directory content may have changed */
  2774. goto begin;
  2775. case SEL_RUNARG:
  2776. run = xgetenv(env, run);
  2777. if ((!run || !run[0]) && (strcmp("VISUAL", env) == 0))
  2778. run = editor ? editor : xgetenv("EDITOR", "vi");
  2779. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2780. break;
  2781. #ifdef __linux__
  2782. case SEL_LOCK:
  2783. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2784. break;
  2785. #endif
  2786. case SEL_CDQUIT:
  2787. {
  2788. char *tmpfile = "/tmp/nnn";
  2789. tmp = getenv("NNN_TMPFILE");
  2790. if (tmp)
  2791. tmpfile = tmp;
  2792. FILE *fp = fopen(tmpfile, "w");
  2793. if (fp) {
  2794. fprintf(fp, "cd \"%s\"", path);
  2795. fclose(fp);
  2796. }
  2797. /* Fall through to exit */
  2798. } // fallthrough
  2799. case SEL_QUIT:
  2800. dentfree(dents);
  2801. return;
  2802. } /* switch (sel) */
  2803. /* Screensaver */
  2804. if (idletimeout != 0 && idle == idletimeout) {
  2805. idle = 0;
  2806. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2807. }
  2808. }
  2809. }
  2810. static void
  2811. usage(void)
  2812. {
  2813. printf("usage: nnn [-b key] [-c N] [-e] [-i] [-l]\n\
  2814. [-p nlay] [-S] [-v] [-h] [PATH]\n\n\
  2815. The missing terminal file browser for X.\n\n\
  2816. positional arguments:\n\
  2817. PATH start dir [default: current dir]\n\n\
  2818. optional arguments:\n\
  2819. -b key specify bookmark key to open\n\
  2820. -c N specify dir color, disables if N>7\n\
  2821. -e use exiftool instead of mediainfo\n\
  2822. -i start in navigate-as-you-type mode\n\
  2823. -l start in light mode (fewer details)\n\
  2824. -p nlay path to custom nlay\n\
  2825. -S start in disk usage analyzer mode\n\
  2826. -v show program version and exit\n\
  2827. -h show this help and exit\n\n\
  2828. Version: %s\n%s\n", VERSION, GENERAL_INFO);
  2829. exit(0);
  2830. }
  2831. int
  2832. main(int argc, char *argv[])
  2833. {
  2834. static char cwd[PATH_MAX] __attribute__ ((aligned));
  2835. char *ipath = NULL, *ifilter, *bmstr;
  2836. int opt;
  2837. /* Confirm we are in a terminal */
  2838. if (!isatty(0) || !isatty(1)) {
  2839. fprintf(stderr, "stdin or stdout is not a tty\n");
  2840. exit(1);
  2841. }
  2842. while ((opt = getopt(argc, argv, "Slib:c:ep:vh")) != -1) {
  2843. switch (opt) {
  2844. case 'S':
  2845. cfg.blkorder = 1;
  2846. break;
  2847. case 'l':
  2848. cfg.showdetail = 0;
  2849. printptr = &printent;
  2850. break;
  2851. case 'i':
  2852. cfg.filtermode = 1;
  2853. break;
  2854. case 'b':
  2855. ipath = optarg;
  2856. break;
  2857. case 'c':
  2858. if (atoi(optarg) > 7)
  2859. cfg.showcolor = 0;
  2860. else
  2861. cfg.color = (uchar)atoi(optarg);
  2862. break;
  2863. case 'e':
  2864. cfg.metaviewer = EXIFTOOL;
  2865. break;
  2866. case 'p':
  2867. player = optarg;
  2868. break;
  2869. case 'v':
  2870. printf("%s\n", VERSION);
  2871. return 0;
  2872. case 'h': // fallthrough
  2873. default:
  2874. usage();
  2875. }
  2876. }
  2877. /* Parse bookmarks string, if available */
  2878. bmstr = getenv("NNN_BMS");
  2879. if (bmstr)
  2880. parsebmstr(bmstr);
  2881. if (ipath) { /* Open a bookmark directly */
  2882. if (get_bm_loc(ipath, cwd) == NULL) {
  2883. fprintf(stderr, "%s\n", messages[STR_INVBM_ID]);
  2884. exit(1);
  2885. }
  2886. ipath = cwd;
  2887. } else if (argc == optind) {
  2888. /* Start in the current directory */
  2889. ipath = getcwd(cwd, PATH_MAX);
  2890. if (ipath == NULL)
  2891. ipath = "/";
  2892. } else {
  2893. ipath = realpath(argv[optind], cwd);
  2894. if (!ipath) {
  2895. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2896. exit(1);
  2897. }
  2898. }
  2899. /* Increase current open file descriptor limit */
  2900. open_max = max_openfds();
  2901. if (getuid() == 0 || getenv("NNN_SHOW_HIDDEN"))
  2902. cfg.showhidden = 1;
  2903. initfilter(cfg.showhidden, &ifilter);
  2904. #ifdef LINUX_INOTIFY
  2905. /* Initialize inotify */
  2906. inotify_fd = inotify_init1(IN_NONBLOCK);
  2907. if (inotify_fd < 0) {
  2908. fprintf(stderr, "inotify init! %s\n", strerror(errno));
  2909. exit(1);
  2910. }
  2911. #elif defined(BSD_KQUEUE)
  2912. kq = kqueue();
  2913. if (kq < 0) {
  2914. fprintf(stderr, "kqueue init! %s\n", strerror(errno));
  2915. exit(1);
  2916. }
  2917. gtimeout.tv_sec = 0;
  2918. gtimeout.tv_nsec = 0;
  2919. #endif
  2920. /* Edit text in EDITOR, if opted */
  2921. if (getenv("NNN_USE_EDITOR")) {
  2922. editor = xgetenv("VISUAL", NULL);
  2923. if (!editor)
  2924. editor = xgetenv("EDITOR", "vi");
  2925. }
  2926. /* Set player if not set already */
  2927. if (!player)
  2928. player = utils[NLAY];
  2929. /* Get the desktop file browser, if set */
  2930. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2931. /* Get screensaver wait time, if set; copier used as tmp var */
  2932. copier = getenv("NNN_IDLE_TIMEOUT");
  2933. if (copier)
  2934. idletimeout = abs(atoi(copier));
  2935. /* Get the default copier, if set */
  2936. copier = getenv("NNN_COPIER");
  2937. /* Enable quotes if opted */
  2938. if (getenv("NNN_QUOTE_ON"))
  2939. cfg.quote = 1;
  2940. /* Check if X11 is available */
  2941. if (getenv("NNN_NO_X")) {
  2942. cfg.noxdisplay = 1;
  2943. struct passwd *pass = getpwuid(getuid());
  2944. xstrlcpy(g_cppath, "/tmp/nnncp", 11);
  2945. xstrlcpy(g_cppath + 10, pass->pw_name, 33);
  2946. }
  2947. signal(SIGINT, SIG_IGN);
  2948. /* Test initial path */
  2949. if (!xdiraccess(ipath)) {
  2950. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2951. exit(1);
  2952. }
  2953. /* Set locale */
  2954. setlocale(LC_ALL, "");
  2955. crc8init();
  2956. #ifdef DEBUGMODE
  2957. enabledbg();
  2958. #endif
  2959. initcurses();
  2960. browse(ipath, ifilter);
  2961. exitcurses();
  2962. #ifdef LINUX_INOTIFY
  2963. /* Shutdown inotify */
  2964. if (inotify_wd >= 0)
  2965. inotify_rm_watch(inotify_fd, inotify_wd);
  2966. close(inotify_fd);
  2967. #elif defined(BSD_KQUEUE)
  2968. if (event_fd >= 0)
  2969. close(event_fd);
  2970. close(kq);
  2971. #endif
  2972. #ifdef DEBUGMODE
  2973. disabledbg();
  2974. #endif
  2975. exit(0);
  2976. }