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.
 
 
 
 
 
 

3342 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.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. /* 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('X'): // fallthrough
  967. case CONTROL('F'): // fallthrough
  968. case CONTROL('T'):
  969. if (len == 1)
  970. cur = oldcur;
  971. goto end;
  972. default:
  973. /* Reset cur in case it's a repeat search */
  974. if (len == 1)
  975. cur = 0;
  976. if (len == REGEX_MAX - 1)
  977. break;
  978. wln[len] = (wchar_t)*ch;
  979. wln[++len] = '\0';
  980. wcstombs(ln, wln, REGEX_MAX);
  981. ndents = total;
  982. if (matches(pln) == -1)
  983. continue;
  984. redraw(path);
  985. printprompt(ln);
  986. }
  987. } else {
  988. if (len == 1)
  989. cur = oldcur;
  990. goto end;
  991. }
  992. }
  993. end:
  994. noecho();
  995. curs_set(FALSE);
  996. settimeout();
  997. /* Return keys for navigation etc. */
  998. return *ch;
  999. }
  1000. /* Show a prompt with input string and return the changes */
  1001. static char *
  1002. xreadline(char *fname)
  1003. {
  1004. int old_curs = curs_set(1);
  1005. size_t len, pos;
  1006. int x, y, r;
  1007. wint_t ch[2] = {0};
  1008. static wchar_t * const buf = (wchar_t *)g_buf;
  1009. if (fname) {
  1010. DPRINTF_S(fname);
  1011. len = pos = mbstowcs(buf, fname, NAME_MAX);
  1012. } else
  1013. len = (size_t)-1;
  1014. if (len == (size_t)-1) {
  1015. buf[0] = '\0';
  1016. len = pos = 0;
  1017. }
  1018. getyx(stdscr, y, x);
  1019. cleartimeout();
  1020. while (1) {
  1021. buf[len] = ' ';
  1022. mvaddnwstr(y, x, buf, len + 1);
  1023. move(y, x + wcswidth(buf, pos));
  1024. if ((r = get_wch(ch)) != ERR) {
  1025. if (r == OK) {
  1026. if (*ch == KEY_ENTER || *ch == '\n' || *ch == '\r')
  1027. break;
  1028. if (*ch == CONTROL('L')) {
  1029. clearprompt();
  1030. len = pos = 0;
  1031. continue;
  1032. }
  1033. /* TAB breaks cursor position, ignore it */
  1034. if (*ch == '\t')
  1035. continue;
  1036. if (pos < NAME_MAX - 1) {
  1037. memmove(buf + pos + 1, buf + pos, (len - pos) << 2);
  1038. buf[pos] = *ch;
  1039. ++len, ++pos;
  1040. continue;
  1041. }
  1042. } else {
  1043. switch (*ch) {
  1044. case KEY_LEFT:
  1045. if (pos > 0)
  1046. --pos;
  1047. break;
  1048. case KEY_RIGHT:
  1049. if (pos < len)
  1050. ++pos;
  1051. break;
  1052. case KEY_BACKSPACE:
  1053. if (pos > 0) {
  1054. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1055. --len, --pos;
  1056. }
  1057. break;
  1058. case KEY_DC:
  1059. if (pos < len) {
  1060. memmove(buf + pos, buf + pos + 1, (len - pos - 1) << 2);
  1061. --len;
  1062. }
  1063. break;
  1064. default:
  1065. break;
  1066. }
  1067. }
  1068. }
  1069. }
  1070. buf[len] = '\0';
  1071. if (old_curs != ERR)
  1072. curs_set(old_curs);
  1073. settimeout();
  1074. DPRINTF_S(buf);
  1075. wcstombs(g_buf, buf, NAME_MAX);
  1076. return g_buf;
  1077. }
  1078. static char *
  1079. readinput(void)
  1080. {
  1081. cleartimeout();
  1082. echo();
  1083. curs_set(TRUE);
  1084. memset(g_buf, 0, NAME_MAX + 1);
  1085. wgetnstr(stdscr, g_buf, NAME_MAX);
  1086. noecho();
  1087. curs_set(FALSE);
  1088. settimeout();
  1089. return g_buf[0] ? g_buf : NULL;
  1090. }
  1091. /*
  1092. * Updates out with "dir/name or "/name"
  1093. * Returns the number of bytes copied including the terminating NULL byte
  1094. */
  1095. size_t
  1096. mkpath(char *dir, char *name, char *out, size_t n)
  1097. {
  1098. static size_t len;
  1099. /* Handle absolute path */
  1100. if (name[0] == '/')
  1101. return xstrlcpy(out, name, n);
  1102. else {
  1103. /* Handle root case */
  1104. if (istopdir(dir))
  1105. len = 1;
  1106. else
  1107. len = xstrlcpy(out, dir, n);
  1108. }
  1109. out[len - 1] = '/';
  1110. return (xstrlcpy(out + len, name, n - len) + len);
  1111. }
  1112. static void
  1113. parsebmstr(char *bms)
  1114. {
  1115. int i = 0;
  1116. while (*bms && i < BM_MAX) {
  1117. bookmark[i].key = bms;
  1118. ++bms;
  1119. while (*bms && *bms != ':')
  1120. ++bms;
  1121. if (!*bms) {
  1122. bookmark[i].key = NULL;
  1123. break;
  1124. }
  1125. *bms = '\0';
  1126. bookmark[i].loc = ++bms;
  1127. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  1128. bookmark[i].key = NULL;
  1129. break;
  1130. }
  1131. while (*bms && *bms != ';')
  1132. ++bms;
  1133. if (*bms)
  1134. *bms = '\0';
  1135. else
  1136. break;
  1137. ++bms;
  1138. ++i;
  1139. }
  1140. }
  1141. /*
  1142. * Get the real path to a bookmark
  1143. *
  1144. * NULL is returned in case of no match, path resolution failure etc.
  1145. * buf would be modified, so check return value before access
  1146. */
  1147. static char *
  1148. get_bm_loc(char *key, char *buf)
  1149. {
  1150. int r;
  1151. if (!key || !key[0])
  1152. return NULL;
  1153. for (r = 0; bookmark[r].key && r < BM_MAX; ++r) {
  1154. if (xstrcmp(bookmark[r].key, key) == 0) {
  1155. if (bookmark[r].loc[0] == '~') {
  1156. char *home = getenv("HOME");
  1157. if (!home) {
  1158. DPRINTF_S(messages[STR_NOHOME_ID]);
  1159. return NULL;
  1160. }
  1161. snprintf(buf, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  1162. } else
  1163. xstrlcpy(buf, bookmark[r].loc, PATH_MAX);
  1164. return buf;
  1165. }
  1166. }
  1167. DPRINTF_S("Invalid key");
  1168. return NULL;
  1169. }
  1170. static void
  1171. resetdircolor(mode_t mode)
  1172. {
  1173. if (cfg.dircolor && !S_ISDIR(mode)) {
  1174. attroff(COLOR_PAIR(1) | A_BOLD);
  1175. cfg.dircolor = 0;
  1176. }
  1177. }
  1178. /*
  1179. * Replace escape characters in a string with '?'
  1180. * Adjust string length to maxcols if > 0;
  1181. *
  1182. * Interestingly, note that unescape() uses g_buf. What happens if
  1183. * str also points to g_buf? In this case we assume that the caller
  1184. * acknowledges that it's OK to lose the data in g_buf after this
  1185. * call to unescape().
  1186. * The API, on its part, first converts str to multibyte (after which
  1187. * it doesn't touch str anymore). Only after that it starts modifying
  1188. * g_buf. This is a phased operation.
  1189. */
  1190. static char *
  1191. unescape(const char *str, uint maxcols)
  1192. {
  1193. static wchar_t wbuf[PATH_MAX] __attribute__ ((aligned));
  1194. static wchar_t *buf;
  1195. static size_t len;
  1196. /* Convert multi-byte to wide char */
  1197. len = mbstowcs(wbuf, str, PATH_MAX);
  1198. g_buf[0] = '\0';
  1199. buf = wbuf;
  1200. if (maxcols && len > maxcols) {
  1201. len = wcswidth(wbuf, len);
  1202. if (len > maxcols)
  1203. wbuf[maxcols] = 0;
  1204. }
  1205. while (*buf) {
  1206. if (*buf <= '\x1f' || *buf == '\x7f')
  1207. *buf = '\?';
  1208. ++buf;
  1209. }
  1210. /* Convert wide char to multi-byte */
  1211. wcstombs(g_buf, wbuf, PATH_MAX);
  1212. return g_buf;
  1213. }
  1214. static char *
  1215. coolsize(off_t size)
  1216. {
  1217. static const char * const U = "BKMGTPEZY";
  1218. static char size_buf[12]; /* Buffer to hold human readable size */
  1219. static int i;
  1220. static long double rem;
  1221. static const double div_2_pow_10 = 1.0 / 1024.0;
  1222. i = 0;
  1223. rem = 0;
  1224. while (size > 1024) {
  1225. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  1226. size >>= 10;
  1227. ++i;
  1228. }
  1229. snprintf(size_buf, 12, "%.*Lf%c", i, size + rem * div_2_pow_10, U[i]);
  1230. return size_buf;
  1231. }
  1232. static char *
  1233. get_file_sym(mode_t mode)
  1234. {
  1235. static char ind[2] = "\0\0";
  1236. if (S_ISDIR(mode))
  1237. ind[0] = '/';
  1238. else if (S_ISLNK(mode))
  1239. ind[0] = '@';
  1240. else if (S_ISSOCK(mode))
  1241. ind[0] = '=';
  1242. else if (S_ISFIFO(mode))
  1243. ind[0] = '|';
  1244. else if (mode & 0100)
  1245. ind[0] = '*';
  1246. else
  1247. ind[0] = '\0';
  1248. return ind;
  1249. }
  1250. static void
  1251. printent(struct entry *ent, int sel, uint namecols)
  1252. {
  1253. static char *pname;
  1254. pname = unescape(ent->name, namecols);
  1255. /* Directories are always shown on top */
  1256. resetdircolor(ent->mode);
  1257. printw("%s%s%s\n", CURSYM(sel), pname, get_file_sym(ent->mode));
  1258. }
  1259. static void
  1260. printent_long(struct entry *ent, int sel, uint namecols)
  1261. {
  1262. static char buf[18], *pname;
  1263. strftime(buf, 18, "%F %R", localtime(&ent->t));
  1264. pname = unescape(ent->name, namecols);
  1265. /* Directories are always shown on top */
  1266. resetdircolor(ent->mode);
  1267. if (sel)
  1268. attron(A_REVERSE);
  1269. if (S_ISDIR(ent->mode)) {
  1270. if (cfg.blkorder)
  1271. printw("%s%-16.16s %8.8s/ %s/\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1272. else
  1273. printw("%s%-16.16s / %s/\n", CURSYM(sel), buf, pname);
  1274. } else if (S_ISLNK(ent->mode))
  1275. printw("%s%-16.16s @ %s@\n", CURSYM(sel), buf, pname);
  1276. else if (S_ISSOCK(ent->mode))
  1277. printw("%s%-16.16s = %s=\n", CURSYM(sel), buf, pname);
  1278. else if (S_ISFIFO(ent->mode))
  1279. printw("%s%-16.16s | %s|\n", CURSYM(sel), buf, pname);
  1280. else if (S_ISBLK(ent->mode))
  1281. printw("%s%-16.16s b %s\n", CURSYM(sel), buf, pname);
  1282. else if (S_ISCHR(ent->mode))
  1283. printw("%s%-16.16s c %s\n", CURSYM(sel), buf, pname);
  1284. else if (ent->mode & 0100) {
  1285. if (cfg.blkorder)
  1286. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1287. else
  1288. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1289. } else {
  1290. if (cfg.blkorder)
  1291. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1292. else
  1293. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1294. }
  1295. if (sel)
  1296. attroff(A_REVERSE);
  1297. }
  1298. static void (*printptr)(struct entry *ent, int sel, uint namecols) = &printent_long;
  1299. static char
  1300. get_fileind(mode_t mode, char *desc)
  1301. {
  1302. static char c;
  1303. if (S_ISREG(mode)) {
  1304. c = '-';
  1305. xstrlcpy(desc, "regular file", DESCRIPTOR_LEN);
  1306. if (mode & 0100)
  1307. xstrlcpy(desc + 12, ", executable", DESCRIPTOR_LEN - 12); /* Length of string "regular file" is 12 */
  1308. } else if (S_ISDIR(mode)) {
  1309. c = 'd';
  1310. xstrlcpy(desc, "directory", DESCRIPTOR_LEN);
  1311. } else if (S_ISBLK(mode)) {
  1312. c = 'b';
  1313. xstrlcpy(desc, "block special device", DESCRIPTOR_LEN);
  1314. } else if (S_ISCHR(mode)) {
  1315. c = 'c';
  1316. xstrlcpy(desc, "character special device", DESCRIPTOR_LEN);
  1317. #ifdef S_ISFIFO
  1318. } else if (S_ISFIFO(mode)) {
  1319. c = 'p';
  1320. xstrlcpy(desc, "FIFO", DESCRIPTOR_LEN);
  1321. #endif /* S_ISFIFO */
  1322. #ifdef S_ISLNK
  1323. } else if (S_ISLNK(mode)) {
  1324. c = 'l';
  1325. xstrlcpy(desc, "symbolic link", DESCRIPTOR_LEN);
  1326. #endif /* S_ISLNK */
  1327. #ifdef S_ISSOCK
  1328. } else if (S_ISSOCK(mode)) {
  1329. c = 's';
  1330. xstrlcpy(desc, "socket", DESCRIPTOR_LEN);
  1331. #endif /* S_ISSOCK */
  1332. #ifdef S_ISDOOR
  1333. /* Solaris 2.6, etc. */
  1334. } else if (S_ISDOOR(mode)) {
  1335. c = 'D';
  1336. desc[0] = '\0';
  1337. #endif /* S_ISDOOR */
  1338. } else {
  1339. /* Unknown type -- possibly a regular file? */
  1340. c = '?';
  1341. desc[0] = '\0';
  1342. }
  1343. return c;
  1344. }
  1345. /* Convert a mode field into "ls -l" type perms field. */
  1346. static char *
  1347. get_lsperms(mode_t mode, char *desc)
  1348. {
  1349. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1350. static char bits[11] = {'\0'};
  1351. bits[0] = get_fileind(mode, desc);
  1352. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  1353. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  1354. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  1355. if (mode & S_ISUID)
  1356. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1357. if (mode & S_ISGID)
  1358. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1359. if (mode & S_ISVTX)
  1360. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1361. return bits;
  1362. }
  1363. /*
  1364. * Gets only a single line (that's what we need
  1365. * for now) or shows full command output in pager.
  1366. *
  1367. * If pager is valid, returns NULL
  1368. */
  1369. static char *
  1370. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager)
  1371. {
  1372. pid_t pid;
  1373. int pipefd[2];
  1374. FILE *pf;
  1375. int tmp, flags;
  1376. char *ret = NULL;
  1377. if (pipe(pipefd) == -1)
  1378. errexit();
  1379. for (tmp = 0; tmp < 2; ++tmp) {
  1380. /* Get previous flags */
  1381. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1382. /* Set bit for non-blocking flag */
  1383. flags |= O_NONBLOCK;
  1384. /* Change flags on fd */
  1385. fcntl(pipefd[tmp], F_SETFL, flags);
  1386. }
  1387. pid = fork();
  1388. if (pid == 0) {
  1389. /* In child */
  1390. close(pipefd[0]);
  1391. dup2(pipefd[1], STDOUT_FILENO);
  1392. dup2(pipefd[1], STDERR_FILENO);
  1393. close(pipefd[1]);
  1394. execlp(file, file, arg1, arg2, NULL);
  1395. _exit(1);
  1396. }
  1397. /* In parent */
  1398. waitpid(pid, &tmp, 0);
  1399. close(pipefd[1]);
  1400. if (!pager) {
  1401. pf = fdopen(pipefd[0], "r");
  1402. if (pf) {
  1403. ret = fgets(buf, bytes, pf);
  1404. close(pipefd[0]);
  1405. }
  1406. return ret;
  1407. }
  1408. pid = fork();
  1409. if (pid == 0) {
  1410. /* Show in pager in child */
  1411. dup2(pipefd[0], STDIN_FILENO);
  1412. close(pipefd[0]);
  1413. execlp("less", "less", NULL);
  1414. _exit(1);
  1415. }
  1416. /* In parent */
  1417. waitpid(pid, &tmp, 0);
  1418. close(pipefd[0]);
  1419. return NULL;
  1420. }
  1421. /*
  1422. * Follows the stat(1) output closely
  1423. */
  1424. static int
  1425. show_stats(char *fpath, char *fname, struct stat *sb)
  1426. {
  1427. char desc[DESCRIPTOR_LEN];
  1428. char *perms = get_lsperms(sb->st_mode, desc);
  1429. char *p, *begin = g_buf;
  1430. char tmp[] = "/tmp/nnnXXXXXX";
  1431. int fd = mkstemp(tmp);
  1432. if (fd == -1)
  1433. return -1;
  1434. dprintf(fd, " File: '%s'", unescape(fname, 0));
  1435. /* Show file name or 'symlink' -> 'target' */
  1436. if (perms[0] == 'l') {
  1437. /* Note that MAX_CMD_LEN > PATH_MAX */
  1438. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1439. if (len != -1) {
  1440. g_buf[len] = '\0';
  1441. /*
  1442. * We pass g_buf but unescape() operates on g_buf too!
  1443. * Read the API notes for information on how this works.
  1444. */
  1445. dprintf(fd, " -> '%s'", unescape(g_buf, 0));
  1446. }
  1447. }
  1448. /* Show size, blocks, file type */
  1449. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1450. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1451. (long long)sb->st_size, (long long)sb->st_blocks, sb->st_blksize, desc);
  1452. #else
  1453. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1454. sb->st_size, sb->st_blocks, (long)sb->st_blksize, desc);
  1455. #endif
  1456. /* Show containing device, inode, hardlink count */
  1457. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1458. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1459. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1460. g_buf, (unsigned long long)sb->st_ino, sb->st_nlink);
  1461. #else
  1462. sprintf(g_buf, "%lxh/%lud", (ulong)sb->st_dev, (ulong)sb->st_dev);
  1463. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1464. g_buf, sb->st_ino, (ulong)sb->st_nlink);
  1465. #endif
  1466. /* Show major, minor number for block or char device */
  1467. if (perms[0] == 'b' || perms[0] == 'c')
  1468. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1469. /* Show permissions, owner, group */
  1470. 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,
  1471. sb->st_mode & 7, perms, sb->st_uid, (getpwuid(sb->st_uid))->pw_name, sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1472. /* Show last access time */
  1473. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_atime));
  1474. dprintf(fd, "\n\n Access: %s", g_buf);
  1475. /* Show last modification time */
  1476. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_mtime));
  1477. dprintf(fd, "\n Modify: %s", g_buf);
  1478. /* Show last status change time */
  1479. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_ctime));
  1480. dprintf(fd, "\n Change: %s", g_buf);
  1481. if (S_ISREG(sb->st_mode)) {
  1482. /* Show file(1) output */
  1483. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1484. if (p) {
  1485. dprintf(fd, "\n\n ");
  1486. while (*p) {
  1487. if (*p == ',') {
  1488. *p = '\0';
  1489. dprintf(fd, " %s\n", begin);
  1490. begin = p + 1;
  1491. }
  1492. ++p;
  1493. }
  1494. dprintf(fd, " %s", begin);
  1495. }
  1496. dprintf(fd, "\n\n");
  1497. } else
  1498. dprintf(fd, "\n\n\n");
  1499. close(fd);
  1500. exitcurses();
  1501. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1502. unlink(tmp);
  1503. refresh();
  1504. return 0;
  1505. }
  1506. static size_t
  1507. get_fs_free(const char *path)
  1508. {
  1509. static struct statvfs svb;
  1510. if (statvfs(path, &svb) == -1)
  1511. return 0;
  1512. else
  1513. return svb.f_bavail << ffs(svb.f_frsize >> 1);
  1514. }
  1515. static size_t
  1516. get_fs_capacity(const char *path)
  1517. {
  1518. struct statvfs svb;
  1519. if (statvfs(path, &svb) == -1)
  1520. return 0;
  1521. else
  1522. return svb.f_blocks << ffs(svb.f_bsize >> 1);
  1523. }
  1524. static int
  1525. show_mediainfo(char *fpath, char *arg)
  1526. {
  1527. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[cfg.metaviewer], NULL, 0))
  1528. return -1;
  1529. exitcurses();
  1530. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, 1);
  1531. refresh();
  1532. return 0;
  1533. }
  1534. static int
  1535. handle_archive(char *fpath, char *arg, char *dir)
  1536. {
  1537. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[ATOOL], NULL, 0))
  1538. return -1;
  1539. if (arg[1] == 'x')
  1540. spawn(utils[ATOOL], arg, fpath, dir, F_NORMAL);
  1541. else {
  1542. exitcurses();
  1543. get_output(NULL, 0, utils[ATOOL], arg, fpath, 1);
  1544. refresh();
  1545. }
  1546. return 0;
  1547. }
  1548. /*
  1549. * The help string tokens (each line) start with a HEX value
  1550. * which indicates the number of spaces to print before the
  1551. * particular token. This method was chosen instead of a flat
  1552. * string because the number of bytes in help was increasing
  1553. * the binary size by around a hundred bytes. This would only
  1554. * have increased as we keep adding new options.
  1555. */
  1556. static int
  1557. show_help(char *path)
  1558. {
  1559. char tmp[] = "/tmp/nnnXXXXXX";
  1560. int i = 0, fd = mkstemp(tmp);
  1561. char *start, *end;
  1562. static char helpstr[] = (
  1563. "cKey | Function\n"
  1564. "e- + -\n"
  1565. "7↑, k, ^P | Previous entry\n"
  1566. "7↓, j, ^N | Next entry\n"
  1567. "7PgUp, ^U | Scroll half page up\n"
  1568. "7PgDn, ^D | Scroll half page down\n"
  1569. "1Home, g, ^, ^A | First entry\n"
  1570. "2End, G, $, ^E | Last entry\n"
  1571. "4→, ↵, l, ^M | Open file or enter dir\n"
  1572. "1←, Bksp, h, ^H | Go to parent dir\n"
  1573. "d^O | Open with...\n"
  1574. "9Insert | Toggle navigate-as-you-type\n"
  1575. "e~ | Go HOME\n"
  1576. "e& | Go to initial dir\n"
  1577. "e- | Go to last visited dir\n"
  1578. "e/ | Filter dir contents\n"
  1579. "d^/ | Open desktop search tool\n"
  1580. "e. | Toggle hide . files\n"
  1581. "d^B | Bookmark prompt\n"
  1582. "eb | Pin current dir\n"
  1583. "d^V | Go to pinned dir\n"
  1584. "ec | Change dir prompt\n"
  1585. "ed | Toggle detail view\n"
  1586. "eD | File details\n"
  1587. "em | Brief media info\n"
  1588. "eM | Full media info\n"
  1589. "en | Create new\n"
  1590. "d^R | Rename entry\n"
  1591. "eR | Rename dir entries\n"
  1592. "es | Toggle sort by size\n"
  1593. "aS, ^J | Toggle du mode\n"
  1594. "et | Toggle sort by mtime\n"
  1595. "e! | Spawn SHELL in dir\n"
  1596. "ee | Edit entry in EDITOR\n"
  1597. "eo | Open dir in file manager\n"
  1598. "ep | Open entry in PAGER\n"
  1599. "eF | List archive\n"
  1600. "d^F | Extract archive\n"
  1601. "d^K | Invoke file path copier\n"
  1602. "d^Y | Toggle multi-copy mode\n"
  1603. "d^T | Toggle path quote\n"
  1604. "d^L | Redraw, clear prompt\n"
  1605. "e? | Help, settings\n"
  1606. "eQ | Quit and cd\n"
  1607. "aq, ^X | Quit\n\n");
  1608. if (fd == -1)
  1609. return -1;
  1610. start = end = helpstr;
  1611. while (*end) {
  1612. while (*end != '\n')
  1613. ++end;
  1614. if (start == end) {
  1615. ++end;
  1616. continue;
  1617. }
  1618. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1619. start = ++end;
  1620. }
  1621. dprintf(fd, "\n");
  1622. if (getenv("NNN_BMS")) {
  1623. dprintf(fd, "BOOKMARKS\n");
  1624. for (; i < BM_MAX; ++i)
  1625. if (bookmark[i].key)
  1626. dprintf(fd, " %s: %s\n", bookmark[i].key, bookmark[i].loc);
  1627. else
  1628. break;
  1629. dprintf(fd, "\n");
  1630. }
  1631. if (editor)
  1632. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1633. if (desktop_manager)
  1634. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1635. if (idletimeout)
  1636. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1637. if (copier)
  1638. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1639. dprintf(fd, "\nVolume: %s of ", coolsize(get_fs_free(path)));
  1640. dprintf(fd, "%s free\n", coolsize(get_fs_capacity(path)));
  1641. dprintf(fd, "\nVersion: %s\n%s\n", VERSION, GENERAL_INFO);
  1642. close(fd);
  1643. exitcurses();
  1644. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1645. unlink(tmp);
  1646. refresh();
  1647. return 0;
  1648. }
  1649. static int
  1650. sum_bsizes(const char *fpath, const struct stat *sb,
  1651. int typeflag, struct FTW *ftwbuf)
  1652. {
  1653. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1654. ent_blocks += sb->st_blocks;
  1655. ++num_files;
  1656. return 0;
  1657. }
  1658. static int
  1659. dentfill(char *path, struct entry **dents,
  1660. int (*filter)(regex_t *, char *), regex_t *re)
  1661. {
  1662. static DIR *dirp;
  1663. static struct dirent *dp;
  1664. static char *namep, *pnb;
  1665. static struct entry *dentp;
  1666. static size_t off, namebuflen = NAMEBUF_INCR;
  1667. static ulong num_saved;
  1668. static int fd, n, count;
  1669. static struct stat sb_path, sb;
  1670. off = 0;
  1671. dirp = opendir(path);
  1672. if (dirp == NULL)
  1673. return 0;
  1674. fd = dirfd(dirp);
  1675. n = 0;
  1676. if (cfg.blkorder) {
  1677. num_files = 0;
  1678. dir_blocks = 0;
  1679. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  1680. printwarn();
  1681. return 0;
  1682. }
  1683. }
  1684. while ((dp = readdir(dirp)) != NULL) {
  1685. namep = dp->d_name;
  1686. if (filter(re, namep) == 0) {
  1687. if (!cfg.blkorder)
  1688. continue;
  1689. /* Skip self and parent */
  1690. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  1691. continue;
  1692. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  1693. continue;
  1694. if (S_ISDIR(sb.st_mode)) {
  1695. if (sb_path.st_dev == sb.st_dev) {
  1696. ent_blocks = 0;
  1697. mkpath(path, namep, g_buf, PATH_MAX);
  1698. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1699. printmsg(messages[STR_NFTWFAIL_ID]);
  1700. dir_blocks += sb.st_blocks;
  1701. } else
  1702. dir_blocks += ent_blocks;
  1703. }
  1704. } else {
  1705. if (sb.st_blocks)
  1706. dir_blocks += sb.st_blocks;
  1707. ++num_files;
  1708. }
  1709. continue;
  1710. }
  1711. /* Skip self and parent */
  1712. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1713. (namep[1] == '.' && namep[2] == '\0'))))
  1714. continue;
  1715. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1716. DPRINTF_S(namep);
  1717. continue;
  1718. }
  1719. if (n == total_dents) {
  1720. total_dents += ENTRY_INCR;
  1721. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  1722. if (*dents == NULL) {
  1723. if (pnamebuf)
  1724. free(pnamebuf);
  1725. errexit();
  1726. }
  1727. DPRINTF_P(*dents);
  1728. }
  1729. /* If there's not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  1730. if (namebuflen - off < NAME_MAX + 1) {
  1731. namebuflen += NAMEBUF_INCR;
  1732. pnb = pnamebuf;
  1733. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  1734. if (pnamebuf == NULL) {
  1735. free(*dents);
  1736. errexit();
  1737. }
  1738. DPRINTF_P(pnamebuf);
  1739. /* realloc() may result in memory move, we must re-adjust if that happens */
  1740. if (pnb != pnamebuf) {
  1741. dentp = *dents;
  1742. dentp->name = pnamebuf;
  1743. for (count = 1; count < n; ++dentp, ++count)
  1744. /* Current filename starts at last filename start + length */
  1745. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  1746. }
  1747. }
  1748. dentp = *dents + n;
  1749. /* Copy file name */
  1750. dentp->name = (char *)((size_t)pnamebuf + off);
  1751. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  1752. off += dentp->nlen;
  1753. /* Copy other fields */
  1754. dentp->mode = sb.st_mode;
  1755. dentp->t = sb.st_mtime;
  1756. dentp->size = sb.st_size;
  1757. if (cfg.blkorder) {
  1758. if (S_ISDIR(sb.st_mode)) {
  1759. ent_blocks = 0;
  1760. num_saved = num_files + 1;
  1761. mkpath(path, namep, g_buf, PATH_MAX);
  1762. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1763. printmsg(messages[STR_NFTWFAIL_ID]);
  1764. dentp->blocks = sb.st_blocks;
  1765. } else
  1766. dentp->blocks = ent_blocks;
  1767. if (sb_path.st_dev == sb.st_dev)
  1768. dir_blocks += dentp->blocks;
  1769. else
  1770. num_files = num_saved;
  1771. } else {
  1772. dentp->blocks = sb.st_blocks;
  1773. dir_blocks += dentp->blocks;
  1774. ++num_files;
  1775. }
  1776. }
  1777. ++n;
  1778. }
  1779. /* Should never be null */
  1780. if (closedir(dirp) == -1) {
  1781. if (*dents) {
  1782. free(pnamebuf);
  1783. free(*dents);
  1784. }
  1785. errexit();
  1786. }
  1787. return n;
  1788. }
  1789. static void
  1790. dentfree(struct entry *dents)
  1791. {
  1792. free(pnamebuf);
  1793. free(dents);
  1794. }
  1795. /* Return the position of the matching entry or 0 otherwise */
  1796. static int
  1797. dentfind(struct entry *dents, const char *fname, int n)
  1798. {
  1799. static int i;
  1800. if (!fname)
  1801. return 0;
  1802. DPRINTF_S(fname);
  1803. for (i = 0; i < n; ++i)
  1804. if (xstrcmp(fname, dents[i].name) == 0)
  1805. return i;
  1806. return 0;
  1807. }
  1808. static int
  1809. populate(char *path, char *oldname, char *fltr)
  1810. {
  1811. static regex_t re;
  1812. /* Can fail when permissions change while browsing.
  1813. * It's assumed that path IS a directory when we are here.
  1814. */
  1815. if (access(path, R_OK) == -1)
  1816. return -1;
  1817. /* Search filter */
  1818. if (setfilter(&re, fltr) != 0)
  1819. return -1;
  1820. if (cfg.blkorder) {
  1821. printmsg("calculating...");
  1822. refresh();
  1823. }
  1824. #ifdef DEBUGMODE
  1825. struct timespec ts1, ts2;
  1826. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  1827. #endif
  1828. ndents = dentfill(path, &dents, visible, &re);
  1829. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1830. #ifdef DEBUGMODE
  1831. clock_gettime(CLOCK_REALTIME, &ts2);
  1832. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  1833. #endif
  1834. /* Find cur from history */
  1835. cur = dentfind(dents, oldname, ndents);
  1836. regfree(&re);
  1837. return 0;
  1838. }
  1839. static void
  1840. redraw(char *path)
  1841. {
  1842. static char buf[(NAME_MAX + 1) << 1] __attribute__ ((aligned));
  1843. static size_t ncols;
  1844. static int nlines, i;
  1845. static bool mode_changed;
  1846. mode_changed = FALSE;
  1847. nlines = MIN(LINES - 4, ndents);
  1848. /* Clean screen */
  1849. erase();
  1850. if (cfg.copymode)
  1851. if (g_crc != crc8fast((uchar *)dents, ndents * sizeof(struct entry))) {
  1852. cfg.copymode = 0;
  1853. DPRINTF_S("copymode off");
  1854. }
  1855. /* Fail redraw if < than 10 columns */
  1856. if (COLS < 10) {
  1857. printmsg("too few columns!");
  1858. return;
  1859. }
  1860. /* Strip trailing slashes */
  1861. for (i = xstrlen(path) - 1; i > 0; --i)
  1862. if (path[i] == '/')
  1863. path[i] = '\0';
  1864. else
  1865. break;
  1866. DPRINTF_D(cur);
  1867. DPRINTF_S(path);
  1868. if (!realpath(path, g_buf)) {
  1869. printwarn();
  1870. return;
  1871. }
  1872. ncols = COLS;
  1873. if (ncols > PATH_MAX)
  1874. ncols = PATH_MAX;
  1875. /* No text wrapping in cwd line */
  1876. /* Show CWD: - xstrlen(CWD) - 1 = 6 */
  1877. g_buf[ncols - 6] = '\0';
  1878. printw(CWD "%s\n\n", g_buf);
  1879. /* Fallback to light mode if less than 35 columns */
  1880. if (ncols < 35 && cfg.showdetail) {
  1881. cfg.showdetail ^= 1;
  1882. printptr = &printent;
  1883. mode_changed = TRUE;
  1884. }
  1885. /* Calculate the number of cols available to print entry name */
  1886. if (cfg.showdetail)
  1887. ncols -= 32;
  1888. else
  1889. ncols -= 5;
  1890. if (cfg.showcolor) {
  1891. attron(COLOR_PAIR(1) | A_BOLD);
  1892. cfg.dircolor = 1;
  1893. }
  1894. /* Print listing */
  1895. if (cur < (nlines >> 1)) {
  1896. for (i = 0; i < nlines; ++i)
  1897. printptr(&dents[i], i == cur, ncols);
  1898. } else if (cur >= ndents - (nlines >> 1)) {
  1899. for (i = ndents - nlines; i < ndents; ++i)
  1900. printptr(&dents[i], i == cur, ncols);
  1901. } else {
  1902. static int odd;
  1903. odd = ISODD(nlines);
  1904. nlines >>= 1;
  1905. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1906. printptr(&dents[i], i == cur, ncols);
  1907. }
  1908. /* Must reset e.g. no files in dir */
  1909. if (cfg.dircolor) {
  1910. attroff(COLOR_PAIR(1) | A_BOLD);
  1911. cfg.dircolor = 0;
  1912. }
  1913. if (cfg.showdetail) {
  1914. if (ndents) {
  1915. static char sort[9];
  1916. if (cfg.mtimeorder)
  1917. xstrlcpy(sort, "by time ", 9);
  1918. else if (cfg.sizeorder)
  1919. xstrlcpy(sort, "by size ", 9);
  1920. else
  1921. sort[0] = '\0';
  1922. /* We need to show filename as it may be truncated in directory listing */
  1923. if (!cfg.blkorder)
  1924. sprintf(buf, "%d/%d %s[%s%s]", cur + 1, ndents, sort, unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  1925. else {
  1926. i = sprintf(buf, "%d/%d du: %s (%lu files) ", cur + 1, ndents, coolsize(dir_blocks << 9), num_files);
  1927. sprintf(buf + i, "vol: %s free [%s%s]",
  1928. coolsize(get_fs_free(path)), unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  1929. }
  1930. printmsg(buf);
  1931. } else
  1932. printmsg("0 items");
  1933. }
  1934. if (mode_changed) {
  1935. cfg.showdetail ^= 1;
  1936. printptr = &printent_long;
  1937. }
  1938. }
  1939. static void
  1940. browse(char *ipath, char *ifilter)
  1941. {
  1942. static char path[PATH_MAX] __attribute__ ((aligned));
  1943. static char newpath[PATH_MAX] __attribute__ ((aligned));
  1944. static char lastdir[PATH_MAX] __attribute__ ((aligned));
  1945. static char mark[PATH_MAX] __attribute__ ((aligned));
  1946. static char fltr[NAME_MAX + 1] __attribute__ ((aligned));
  1947. static char oldname[NAME_MAX + 1] __attribute__ ((aligned));
  1948. char *dir, *tmp, *run = NULL, *env = NULL;
  1949. struct stat sb;
  1950. int r, fd, presel, copystartid = 0, copyendid = 0;
  1951. enum action sel = SEL_RUNARG + 1;
  1952. bool dir_changed = FALSE;
  1953. xstrlcpy(path, ipath, PATH_MAX);
  1954. copyfilter();
  1955. oldname[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  1956. if (cfg.filtermode)
  1957. presel = FILTER;
  1958. else
  1959. presel = 0;
  1960. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  1961. if (dents == NULL)
  1962. errexit();
  1963. DPRINTF_P(dents);
  1964. /* Allocate buffer to hold names */
  1965. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  1966. if (pnamebuf == NULL) {
  1967. free(dents);
  1968. errexit();
  1969. }
  1970. DPRINTF_P(pnamebuf);
  1971. begin:
  1972. #ifdef LINUX_INOTIFY
  1973. if (dir_changed && inotify_wd >= 0) {
  1974. inotify_rm_watch(inotify_fd, inotify_wd);
  1975. inotify_wd = -1;
  1976. dir_changed = FALSE;
  1977. }
  1978. #elif defined(BSD_KQUEUE)
  1979. if (dir_changed && event_fd >= 0) {
  1980. close(event_fd);
  1981. event_fd = -1;
  1982. dir_changed = FALSE;
  1983. }
  1984. #endif
  1985. if (populate(path, oldname, fltr) == -1) {
  1986. printwarn();
  1987. goto nochange;
  1988. }
  1989. #ifdef LINUX_INOTIFY
  1990. if (inotify_wd == -1)
  1991. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  1992. #elif defined(BSD_KQUEUE)
  1993. if (event_fd == -1) {
  1994. #if defined(O_EVTONLY)
  1995. event_fd = open(path, O_EVTONLY);
  1996. #else
  1997. event_fd = open(path, O_RDONLY);
  1998. #endif
  1999. if (event_fd >= 0)
  2000. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  2001. }
  2002. #endif
  2003. for (;;) {
  2004. redraw(path);
  2005. nochange:
  2006. /* Exit if parent has exited */
  2007. if (getppid() == 1)
  2008. _exit(0);
  2009. sel = nextsel(&run, &env, &presel);
  2010. switch (sel) {
  2011. case SEL_BACK:
  2012. /* There is no going back */
  2013. if (istopdir(path)) {
  2014. printmsg(messages[STR_ATROOT_ID]);
  2015. goto nochange;
  2016. }
  2017. dir = xdirname(path);
  2018. if (access(dir, R_OK) == -1) {
  2019. printwarn();
  2020. goto nochange;
  2021. }
  2022. /* Save history */
  2023. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2024. /* Save last working directory */
  2025. xstrlcpy(lastdir, path, PATH_MAX);
  2026. dir_changed = TRUE;
  2027. xstrlcpy(path, dir, PATH_MAX);
  2028. /* Reset filter */
  2029. copyfilter();
  2030. if (cfg.filtermode)
  2031. presel = FILTER;
  2032. goto begin;
  2033. case SEL_GOIN:
  2034. /* Cannot descend in empty directories */
  2035. if (ndents == 0)
  2036. goto begin;
  2037. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2038. DPRINTF_S(newpath);
  2039. /* Get path info */
  2040. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  2041. if (fd == -1) {
  2042. printwarn();
  2043. goto nochange;
  2044. }
  2045. if (fstat(fd, &sb) == -1) {
  2046. printwarn();
  2047. close(fd);
  2048. goto nochange;
  2049. }
  2050. close(fd);
  2051. DPRINTF_U(sb.st_mode);
  2052. switch (sb.st_mode & S_IFMT) {
  2053. case S_IFDIR:
  2054. if (access(newpath, R_OK) == -1) {
  2055. printwarn();
  2056. goto nochange;
  2057. }
  2058. /* Save last working directory */
  2059. xstrlcpy(lastdir, path, PATH_MAX);
  2060. dir_changed = TRUE;
  2061. xstrlcpy(path, newpath, PATH_MAX);
  2062. oldname[0] = '\0';
  2063. /* Reset filter */
  2064. copyfilter();
  2065. if (cfg.filtermode)
  2066. presel = FILTER;
  2067. goto begin;
  2068. case S_IFREG:
  2069. {
  2070. /* If NNN_USE_EDITOR is set,
  2071. * open text in EDITOR
  2072. */
  2073. if (editor) {
  2074. if (getmime(dents[cur].name)) {
  2075. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  2076. continue;
  2077. }
  2078. /* Recognize and open plain
  2079. * text files with vi
  2080. */
  2081. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  2082. continue;
  2083. if (strstr(g_buf, "text/") == g_buf) {
  2084. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  2085. continue;
  2086. }
  2087. }
  2088. /* Invoke desktop opener as last resort */
  2089. spawn(utils[OPENER], newpath, NULL, NULL, nowait);
  2090. continue;
  2091. }
  2092. default:
  2093. printmsg("unsupported file");
  2094. goto nochange;
  2095. }
  2096. case SEL_NEXT:
  2097. if (cur < ndents - 1)
  2098. ++cur;
  2099. else if (ndents)
  2100. /* Roll over, set cursor to first entry */
  2101. cur = 0;
  2102. break;
  2103. case SEL_PREV:
  2104. if (cur > 0)
  2105. --cur;
  2106. else if (ndents)
  2107. /* Roll over, set cursor to last entry */
  2108. cur = ndents - 1;
  2109. break;
  2110. case SEL_PGDN:
  2111. if (cur < ndents - 1)
  2112. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  2113. break;
  2114. case SEL_PGUP:
  2115. if (cur > 0)
  2116. cur -= MIN((LINES - 4) / 2, cur);
  2117. break;
  2118. case SEL_HOME:
  2119. cur = 0;
  2120. break;
  2121. case SEL_END:
  2122. cur = ndents - 1;
  2123. break;
  2124. case SEL_CD:
  2125. {
  2126. char *input;
  2127. int truecd;
  2128. /* Save the program start dir */
  2129. tmp = getcwd(newpath, PATH_MAX);
  2130. if (tmp == NULL) {
  2131. printwarn();
  2132. goto nochange;
  2133. }
  2134. /* Switch to current path for readline(3) */
  2135. if (chdir(path) == -1) {
  2136. printwarn();
  2137. goto nochange;
  2138. }
  2139. exitcurses();
  2140. tmp = readline("chdir: ");
  2141. refresh();
  2142. /* Change back to program start dir */
  2143. if (chdir(newpath) == -1)
  2144. printwarn();
  2145. if (tmp[0] == '\0')
  2146. break;
  2147. /* Add to readline(3) history */
  2148. add_history(tmp);
  2149. input = tmp;
  2150. tmp = strstrip(tmp);
  2151. if (tmp[0] == '\0') {
  2152. free(input);
  2153. break;
  2154. }
  2155. truecd = 0;
  2156. if (tmp[0] == '~') {
  2157. /* Expand ~ to HOME absolute path */
  2158. char *home = getenv("HOME");
  2159. if (home)
  2160. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  2161. else {
  2162. free(input);
  2163. printmsg(messages[STR_NOHOME_ID]);
  2164. goto nochange;
  2165. }
  2166. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  2167. if (lastdir[0] == '\0') {
  2168. free(input);
  2169. break;
  2170. }
  2171. /* Switch to last visited dir */
  2172. xstrlcpy(newpath, lastdir, PATH_MAX);
  2173. truecd = 1;
  2174. } else if ((r = all_dots(tmp))) {
  2175. if (r == 1) {
  2176. /* Always in the current dir */
  2177. free(input);
  2178. break;
  2179. }
  2180. /* Show a message if already at / */
  2181. if (istopdir(path)) {
  2182. printmsg(messages[STR_ATROOT_ID]);
  2183. free(input);
  2184. goto nochange;
  2185. }
  2186. --r; /* One . for the current dir */
  2187. dir = path;
  2188. /* Note: fd is used as a tmp variable here */
  2189. for (fd = 0; fd < r; ++fd) {
  2190. /* Reached / ? */
  2191. if (istopdir(path)) {
  2192. /* Can't cd beyond / */
  2193. break;
  2194. }
  2195. dir = xdirname(dir);
  2196. if (access(dir, R_OK) == -1) {
  2197. printwarn();
  2198. free(input);
  2199. goto nochange;
  2200. }
  2201. }
  2202. truecd = 1;
  2203. /* Save the path in case of cd ..
  2204. * We mark the current dir in parent dir
  2205. */
  2206. if (r == 1) {
  2207. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2208. truecd = 2;
  2209. }
  2210. xstrlcpy(newpath, dir, PATH_MAX);
  2211. } else
  2212. mkpath(path, tmp, newpath, PATH_MAX);
  2213. free(input);
  2214. if (!xdiraccess(newpath))
  2215. goto nochange;
  2216. if (truecd == 0) {
  2217. /* Probable change in dir */
  2218. /* No-op if it's the same directory */
  2219. if (xstrcmp(path, newpath) == 0)
  2220. break;
  2221. oldname[0] = '\0';
  2222. } else if (truecd == 1)
  2223. /* Sure change in dir */
  2224. oldname[0] = '\0';
  2225. /* Save last working directory */
  2226. xstrlcpy(lastdir, path, PATH_MAX);
  2227. dir_changed = TRUE;
  2228. /* Save the newly opted dir in path */
  2229. xstrlcpy(path, newpath, PATH_MAX);
  2230. /* Reset filter */
  2231. copyfilter();
  2232. DPRINTF_S(path);
  2233. if (cfg.filtermode)
  2234. presel = FILTER;
  2235. goto begin;
  2236. }
  2237. case SEL_CDHOME:
  2238. dir = getenv("HOME");
  2239. if (dir == NULL) {
  2240. clearprompt();
  2241. goto nochange;
  2242. } // fallthrough
  2243. case SEL_CDBEGIN:
  2244. if (sel == SEL_CDBEGIN)
  2245. dir = ipath;
  2246. if (!xdiraccess(dir)) {
  2247. goto nochange;
  2248. }
  2249. if (xstrcmp(path, dir) == 0) {
  2250. break;
  2251. }
  2252. /* Save last working directory */
  2253. xstrlcpy(lastdir, path, PATH_MAX);
  2254. dir_changed = TRUE;
  2255. xstrlcpy(path, dir, PATH_MAX);
  2256. oldname[0] = '\0';
  2257. /* Reset filter */
  2258. copyfilter();
  2259. DPRINTF_S(path);
  2260. if (cfg.filtermode)
  2261. presel = FILTER;
  2262. goto begin;
  2263. case SEL_CDLAST: // fallthrough
  2264. case SEL_VISIT:
  2265. if (sel == SEL_VISIT) {
  2266. if (xstrcmp(mark, path) == 0)
  2267. break;
  2268. tmp = mark;
  2269. } else
  2270. tmp = lastdir;
  2271. if (tmp[0] == '\0') {
  2272. printmsg("not set...");
  2273. goto nochange;
  2274. }
  2275. if (!xdiraccess(tmp))
  2276. goto nochange;
  2277. xstrlcpy(newpath, tmp, PATH_MAX);
  2278. xstrlcpy(lastdir, path, PATH_MAX);
  2279. dir_changed = TRUE;
  2280. xstrlcpy(path, newpath, PATH_MAX);
  2281. oldname[0] = '\0';
  2282. /* Reset filter */
  2283. copyfilter();
  2284. DPRINTF_S(path);
  2285. if (cfg.filtermode)
  2286. presel = FILTER;
  2287. goto begin;
  2288. case SEL_CDBM:
  2289. printprompt("key: ");
  2290. tmp = readinput();
  2291. clearprompt();
  2292. if (tmp == NULL)
  2293. break;
  2294. if (get_bm_loc(tmp, newpath) == NULL) {
  2295. printmsg(messages[STR_INVBM_ID]);
  2296. goto nochange;
  2297. }
  2298. if (!xdiraccess(newpath))
  2299. goto nochange;
  2300. if (xstrcmp(path, newpath) == 0)
  2301. break;
  2302. oldname[0] = '\0';
  2303. /* Save last working directory */
  2304. xstrlcpy(lastdir, path, PATH_MAX);
  2305. dir_changed = TRUE;
  2306. /* Save the newly opted dir in path */
  2307. xstrlcpy(path, newpath, PATH_MAX);
  2308. /* Reset filter */
  2309. copyfilter();
  2310. DPRINTF_S(path);
  2311. if (cfg.filtermode)
  2312. presel = FILTER;
  2313. goto begin;
  2314. case SEL_PIN:
  2315. xstrlcpy(mark, path, PATH_MAX);
  2316. printmsg(mark);
  2317. goto nochange;
  2318. case SEL_FLTR:
  2319. presel = filterentries(path);
  2320. copyfilter();
  2321. DPRINTF_S(fltr);
  2322. /* Save current */
  2323. if (ndents > 0)
  2324. copycurname();
  2325. goto nochange;
  2326. case SEL_MFLTR:
  2327. cfg.filtermode ^= 1;
  2328. if (cfg.filtermode)
  2329. presel = FILTER;
  2330. else {
  2331. /* Save current */
  2332. if (ndents > 0)
  2333. copycurname();
  2334. /* Start watching the directory */
  2335. goto begin;
  2336. }
  2337. goto nochange;
  2338. case SEL_SEARCH:
  2339. spawn(player, path, "search", NULL, F_NORMAL);
  2340. break;
  2341. case SEL_TOGGLEDOT:
  2342. cfg.showhidden ^= 1;
  2343. initfilter(cfg.showhidden, &ifilter);
  2344. copyfilter();
  2345. goto begin;
  2346. case SEL_DETAIL:
  2347. cfg.showdetail ^= 1;
  2348. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2349. /* Save current */
  2350. if (ndents > 0)
  2351. copycurname();
  2352. goto begin;
  2353. case SEL_STATS:
  2354. if (ndents > 0) {
  2355. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2356. if (lstat(newpath, &sb) == -1) {
  2357. if (dents)
  2358. dentfree(dents);
  2359. errexit();
  2360. } else {
  2361. if (show_stats(newpath, dents[cur].name, &sb) < 0) {
  2362. printwarn();
  2363. goto nochange;
  2364. }
  2365. }
  2366. }
  2367. break;
  2368. case SEL_LIST: // fallthrough
  2369. case SEL_EXTRACT: // fallthrough
  2370. case SEL_MEDIA: // fallthrough
  2371. case SEL_FMEDIA:
  2372. if (ndents > 0) {
  2373. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2374. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2375. r = show_mediainfo(newpath, run);
  2376. else
  2377. r = handle_archive(newpath, run, path);
  2378. if (r == -1) {
  2379. xstrlcpy(newpath, "missing ", PATH_MAX);
  2380. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2381. xstrlcpy(newpath + 8, utils[cfg.metaviewer], 32);
  2382. else
  2383. xstrlcpy(newpath + 8, utils[ATOOL], 32);
  2384. printmsg(newpath);
  2385. goto nochange;
  2386. }
  2387. }
  2388. break;
  2389. case SEL_DFB:
  2390. if (!desktop_manager) {
  2391. printmsg("set NNN_DE_FILE_MANAGER");
  2392. goto nochange;
  2393. }
  2394. spawn(desktop_manager, path, NULL, path, F_NOTRACE | F_NOWAIT);
  2395. break;
  2396. case SEL_FSIZE:
  2397. cfg.sizeorder ^= 1;
  2398. cfg.mtimeorder = 0;
  2399. cfg.blkorder = 0;
  2400. cfg.copymode = 0;
  2401. /* Save current */
  2402. if (ndents > 0)
  2403. copycurname();
  2404. goto begin;
  2405. case SEL_BSIZE:
  2406. cfg.blkorder ^= 1;
  2407. if (cfg.blkorder) {
  2408. cfg.showdetail = 1;
  2409. printptr = &printent_long;
  2410. }
  2411. cfg.mtimeorder = 0;
  2412. cfg.sizeorder = 0;
  2413. cfg.copymode = 0;
  2414. /* Save current */
  2415. if (ndents > 0)
  2416. copycurname();
  2417. goto begin;
  2418. case SEL_MTIME:
  2419. cfg.mtimeorder ^= 1;
  2420. cfg.sizeorder = 0;
  2421. cfg.blkorder = 0;
  2422. cfg.copymode = 0;
  2423. /* Save current */
  2424. if (ndents > 0)
  2425. copycurname();
  2426. goto begin;
  2427. case SEL_REDRAW:
  2428. /* Save current */
  2429. if (ndents > 0)
  2430. copycurname();
  2431. goto begin;
  2432. case SEL_COPY:
  2433. if (copier && ndents) {
  2434. if (cfg.copymode) {
  2435. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2436. if (!appendfilepath(newpath, r))
  2437. goto nochange;
  2438. printmsg(newpath);
  2439. } else if (cfg.quote) {
  2440. g_buf[0] = '\'';
  2441. r = mkpath(path, dents[cur].name, g_buf + 1, PATH_MAX);
  2442. g_buf[r] = '\'';
  2443. g_buf[r + 1] = '\0';
  2444. if (cfg.noxdisplay)
  2445. writecp(g_buf, r + 1); /* Truncate NULL from end */
  2446. else
  2447. spawn(copier, g_buf, NULL, NULL, F_NONE);
  2448. g_buf[r] = '\0';
  2449. printmsg(g_buf + 1);
  2450. } else {
  2451. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2452. if (cfg.noxdisplay)
  2453. writecp(newpath, r - 1); /* Truncate NULL from end */
  2454. else
  2455. spawn(copier, newpath, NULL, NULL, F_NONE);
  2456. printmsg(newpath);
  2457. }
  2458. } else if (!copier)
  2459. printmsg(messages[STR_COPY_ID]);
  2460. goto nochange;
  2461. case SEL_COPYMUL:
  2462. if (!copier) {
  2463. printmsg(messages[STR_COPY_ID]);
  2464. goto nochange;
  2465. } else if (!ndents) {
  2466. goto nochange;
  2467. }
  2468. cfg.copymode ^= 1;
  2469. if (cfg.copymode) {
  2470. g_crc = crc8fast((uchar *)dents, ndents * sizeof(struct entry));
  2471. copystartid = cur;
  2472. copybufpos = 0;
  2473. printmsg("multi-copy on");
  2474. DPRINTF_S("copymode on");
  2475. } else {
  2476. static size_t len;
  2477. len = 0;
  2478. /* Handle range selection */
  2479. if (copybufpos == 0) {
  2480. if (cur < copystartid) {
  2481. copyendid = copystartid;
  2482. copystartid = cur;
  2483. } else
  2484. copyendid = cur;
  2485. if (copystartid < copyendid) {
  2486. for (r = copystartid; r <= copyendid; ++r) {
  2487. len = mkpath(path, dents[r].name, newpath, PATH_MAX);
  2488. if (!appendfilepath(newpath, len))
  2489. goto nochange;;
  2490. }
  2491. sprintf(newpath, "%d files copied", copyendid - copystartid + 1);
  2492. printmsg(newpath);
  2493. }
  2494. }
  2495. if (copybufpos) {
  2496. if (cfg.noxdisplay)
  2497. writecp(pcopybuf, copybufpos - 1); /* Truncate NULL from end */
  2498. else
  2499. spawn(copier, pcopybuf, NULL, NULL, F_NONE);
  2500. DPRINTF_S(pcopybuf);
  2501. if (!len)
  2502. printmsg("files copied");
  2503. } else
  2504. printmsg("multi-copy off");
  2505. }
  2506. goto nochange;
  2507. case SEL_QUOTE:
  2508. cfg.quote ^= 1;
  2509. DPRINTF_D(cfg.quote);
  2510. if (cfg.quote)
  2511. printmsg("quotes on");
  2512. else
  2513. printmsg("quotes off");
  2514. goto nochange;
  2515. case SEL_OPEN:
  2516. printprompt("open with: "); // fallthrough
  2517. case SEL_NEW:
  2518. if (sel == SEL_NEW)
  2519. printprompt("name: ");
  2520. tmp = xreadline(NULL);
  2521. clearprompt();
  2522. if (tmp == NULL || tmp[0] == '\0')
  2523. break;
  2524. /* Allow only relative, same dir paths */
  2525. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  2526. printmsg(messages[STR_INPUT_ID]);
  2527. goto nochange;
  2528. }
  2529. if (sel == SEL_OPEN) {
  2530. printprompt("press 'c' for cli mode");
  2531. cleartimeout();
  2532. r = getch();
  2533. settimeout();
  2534. if (r == 'c')
  2535. r = F_NORMAL;
  2536. else
  2537. r = F_NOWAIT | F_NOTRACE;
  2538. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2539. spawn(tmp, newpath, NULL, path, r);
  2540. continue;
  2541. }
  2542. /* Open the descriptor to currently open directory */
  2543. fd = open(path, O_RDONLY | O_DIRECTORY);
  2544. if (fd == -1) {
  2545. printwarn();
  2546. goto nochange;
  2547. }
  2548. /* Check if another file with same name exists */
  2549. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2550. printmsg("entry exists");
  2551. goto nochange;
  2552. }
  2553. /* Check if it's a dir or file */
  2554. printprompt("press 'f'(ile) or 'd'(ir)");
  2555. cleartimeout();
  2556. r = getch();
  2557. settimeout();
  2558. if (r == 'f') {
  2559. r = openat(fd, tmp, O_CREAT, 0666);
  2560. close(r);
  2561. } else if (r == 'd')
  2562. r = mkdirat(fd, tmp, 0777);
  2563. else {
  2564. close(fd);
  2565. break;
  2566. }
  2567. if (r == -1) {
  2568. printwarn();
  2569. close(fd);
  2570. goto nochange;
  2571. }
  2572. close(fd);
  2573. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2574. goto begin;
  2575. case SEL_RENAME:
  2576. if (ndents <= 0)
  2577. break;
  2578. printprompt("");
  2579. tmp = xreadline(dents[cur].name);
  2580. clearprompt();
  2581. if (tmp == NULL || tmp[0] == '\0')
  2582. break;
  2583. /* Allow only relative, same dir paths */
  2584. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  2585. printmsg(messages[STR_INPUT_ID]);
  2586. goto nochange;
  2587. }
  2588. /* Skip renaming to same name */
  2589. if (xstrcmp(tmp, dents[cur].name) == 0)
  2590. break;
  2591. /* Open the descriptor to currently open directory */
  2592. fd = open(path, O_RDONLY | O_DIRECTORY);
  2593. if (fd == -1) {
  2594. printwarn();
  2595. goto nochange;
  2596. }
  2597. /* Check if another file with same name exists */
  2598. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2599. /* File with the same name exists */
  2600. printprompt("press 'y' to overwrite");
  2601. cleartimeout();
  2602. r = getch();
  2603. settimeout();
  2604. if (r != 'y') {
  2605. close(fd);
  2606. break;
  2607. }
  2608. }
  2609. /* Rename the file */
  2610. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  2611. printwarn();
  2612. close(fd);
  2613. goto nochange;
  2614. }
  2615. close(fd);
  2616. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2617. goto begin;
  2618. case SEL_RENAMEALL:
  2619. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[VIDIR], NULL, 0)) {
  2620. printmsg("vidir missing");
  2621. goto nochange;
  2622. }
  2623. /* Save the program start dir */
  2624. tmp = getcwd(newpath, PATH_MAX);
  2625. if (tmp == NULL) {
  2626. printwarn();
  2627. goto nochange;
  2628. }
  2629. /* Switch to current path for readline(3) */
  2630. if (chdir(path) == -1) {
  2631. printwarn();
  2632. goto nochange;
  2633. }
  2634. spawn(utils[VIDIR], ".", NULL, NULL, F_NORMAL);
  2635. /* Change back to program start dir */
  2636. if (chdir(newpath) == -1)
  2637. printwarn();
  2638. /* Save current */
  2639. if (ndents > 0)
  2640. copycurname();
  2641. goto begin;
  2642. case SEL_HELP:
  2643. show_help(path);
  2644. break;
  2645. case SEL_RUN:
  2646. run = xgetenv(env, run);
  2647. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2648. /* Repopulate as directory content may have changed */
  2649. /* Save current */
  2650. if (ndents > 0)
  2651. copycurname();
  2652. goto begin;
  2653. case SEL_RUNARG:
  2654. run = xgetenv(env, run);
  2655. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2656. break;
  2657. case SEL_CDQUIT:
  2658. {
  2659. char *tmpfile = "/tmp/nnn";
  2660. tmp = getenv("NNN_TMPFILE");
  2661. if (tmp)
  2662. tmpfile = tmp;
  2663. FILE *fp = fopen(tmpfile, "w");
  2664. if (fp) {
  2665. fprintf(fp, "cd \"%s\"", path);
  2666. fclose(fp);
  2667. }
  2668. /* Fall through to exit */
  2669. } // fallthrough
  2670. case SEL_QUIT:
  2671. dentfree(dents);
  2672. return;
  2673. }
  2674. /* Screensaver */
  2675. if (idletimeout != 0 && idle == idletimeout) {
  2676. idle = 0;
  2677. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2678. }
  2679. }
  2680. }
  2681. static void
  2682. usage(void)
  2683. {
  2684. printf("usage: nnn [-b key] [-c N] [-e] [-i] [-l]\n\
  2685. [-p nlay] [-S] [-v] [-h] [PATH]\n\n\
  2686. The missing terminal file browser for X.\n\n\
  2687. positional arguments:\n\
  2688. PATH start dir [default: current dir]\n\n\
  2689. optional arguments:\n\
  2690. -b key specify bookmark key to open\n\
  2691. -c N specify dir color, disables if N>7\n\
  2692. -e use exiftool instead of mediainfo\n\
  2693. -i start in navigate-as-you-type mode\n\
  2694. -l start in light mode (fewer details)\n\
  2695. -p nlay path to custom nlay\n\
  2696. -S start in disk usage analyzer mode\n\
  2697. -v show program version and exit\n\
  2698. -h show this help and exit\n\n\
  2699. Version: %s\n%s\n", VERSION, GENERAL_INFO);
  2700. exit(0);
  2701. }
  2702. int
  2703. main(int argc, char *argv[])
  2704. {
  2705. static char cwd[PATH_MAX] __attribute__ ((aligned));
  2706. char *ipath = NULL, *ifilter, *bmstr;
  2707. int opt;
  2708. /* Confirm we are in a terminal */
  2709. if (!isatty(0) || !isatty(1)) {
  2710. fprintf(stderr, "stdin or stdout is not a tty\n");
  2711. exit(1);
  2712. }
  2713. while ((opt = getopt(argc, argv, "Slib:c:ep:vh")) != -1) {
  2714. switch (opt) {
  2715. case 'S':
  2716. cfg.blkorder = 1;
  2717. break;
  2718. case 'l':
  2719. cfg.showdetail = 0;
  2720. printptr = &printent;
  2721. break;
  2722. case 'i':
  2723. cfg.filtermode = 1;
  2724. break;
  2725. case 'b':
  2726. ipath = optarg;
  2727. break;
  2728. case 'c':
  2729. if (atoi(optarg) > 7)
  2730. cfg.showcolor = 0;
  2731. else
  2732. cfg.color = (uchar)atoi(optarg);
  2733. break;
  2734. case 'e':
  2735. cfg.metaviewer = EXIFTOOL;
  2736. break;
  2737. case 'p':
  2738. player = optarg;
  2739. break;
  2740. case 'v':
  2741. printf("%s\n", VERSION);
  2742. return 0;
  2743. case 'h': // fallthrough
  2744. default:
  2745. usage();
  2746. }
  2747. }
  2748. /* Parse bookmarks string, if available */
  2749. bmstr = getenv("NNN_BMS");
  2750. if (bmstr)
  2751. parsebmstr(bmstr);
  2752. if (ipath) { /* Open a bookmark directly */
  2753. if (get_bm_loc(ipath, cwd) == NULL) {
  2754. fprintf(stderr, "%s\n", messages[STR_INVBM_ID]);
  2755. exit(1);
  2756. }
  2757. ipath = cwd;
  2758. } else if (argc == optind) {
  2759. /* Start in the current directory */
  2760. ipath = getcwd(cwd, PATH_MAX);
  2761. if (ipath == NULL)
  2762. ipath = "/";
  2763. } else {
  2764. ipath = realpath(argv[optind], cwd);
  2765. if (!ipath) {
  2766. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2767. exit(1);
  2768. }
  2769. }
  2770. /* Increase current open file descriptor limit */
  2771. open_max = max_openfds();
  2772. if (getuid() == 0)
  2773. cfg.showhidden = 1;
  2774. initfilter(cfg.showhidden, &ifilter);
  2775. #ifdef LINUX_INOTIFY
  2776. /* Initialize inotify */
  2777. inotify_fd = inotify_init1(IN_NONBLOCK);
  2778. if (inotify_fd < 0) {
  2779. fprintf(stderr, "inotify init! %s\n", strerror(errno));
  2780. exit(1);
  2781. }
  2782. #elif defined(BSD_KQUEUE)
  2783. kq = kqueue();
  2784. if (kq < 0) {
  2785. fprintf(stderr, "kqueue init! %s\n", strerror(errno));
  2786. exit(1);
  2787. }
  2788. gtimeout.tv_sec = 0;
  2789. gtimeout.tv_nsec = 0;
  2790. #endif
  2791. /* Edit text in EDITOR, if opted */
  2792. if (getenv("NNN_USE_EDITOR"))
  2793. editor = xgetenv("EDITOR", "vi");
  2794. /* Set player if not set already */
  2795. if (!player)
  2796. player = utils[NLAY];
  2797. /* Get the desktop file browser, if set */
  2798. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2799. /* Get screensaver wait time, if set; copier used as tmp var */
  2800. copier = getenv("NNN_IDLE_TIMEOUT");
  2801. if (copier)
  2802. idletimeout = abs(atoi(copier));
  2803. /* Get the default copier, if set */
  2804. copier = getenv("NNN_COPIER");
  2805. /* Get nowait flag */
  2806. nowait |= getenv("NNN_NOWAIT") ? F_NOWAIT : 0;
  2807. /* Enable quotes if opted */
  2808. if (getenv("NNN_QUOTE_ON"))
  2809. cfg.quote = 1;
  2810. /* Check if X11 is available */
  2811. if (getenv("NNN_NO_X"))
  2812. cfg.noxdisplay = 1;
  2813. signal(SIGINT, SIG_IGN);
  2814. /* Test initial path */
  2815. if (!xdiraccess(ipath)) {
  2816. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2817. exit(1);
  2818. }
  2819. /* Set locale */
  2820. setlocale(LC_ALL, "");
  2821. crc8init();
  2822. #ifdef DEBUGMODE
  2823. enabledbg();
  2824. #endif
  2825. initcurses();
  2826. browse(ipath, ifilter);
  2827. exitcurses();
  2828. #ifdef LINUX_INOTIFY
  2829. /* Shutdown inotify */
  2830. if (inotify_wd >= 0)
  2831. inotify_rm_watch(inotify_fd, inotify_wd);
  2832. close(inotify_fd);
  2833. #elif defined(BSD_KQUEUE)
  2834. if (event_fd >= 0)
  2835. close(event_fd);
  2836. close(kq);
  2837. #endif
  2838. #ifdef DEBUGMODE
  2839. disabledbg();
  2840. #endif
  2841. exit(0);
  2842. }