My build of nnn with minor changes
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

3524 řádky
75 KiB

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