My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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