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

3479 satır
74 KiB

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