My build of nnn with minor changes
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

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