My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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