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

3452 行
74 KiB

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