My build of nnn with minor changes
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

3353 行
70 KiB

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