My build of nnn with minor changes
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

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