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.
 
 
 
 
 
 

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