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.
 
 
 
 
 
 

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