My build of nnn with minor changes
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

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