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.
 
 
 
 
 
 

3303 lines
69 KiB

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