My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2440 lines
49 KiB

  1. /* See LICENSE file for copyright and license details. */
  2. #include <sys/stat.h>
  3. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  4. || defined(__APPLE__)
  5. # include <sys/types.h>
  6. #else
  7. # include <sys/sysmacros.h>
  8. #endif
  9. #include <sys/wait.h>
  10. #include <sys/statvfs.h>
  11. #include <sys/resource.h>
  12. #include <ctype.h>
  13. #include <curses.h>
  14. #include <dirent.h>
  15. #include <errno.h>
  16. #include <fcntl.h>
  17. #include <grp.h>
  18. #include <libgen.h>
  19. #include <limits.h>
  20. #ifdef __gnu_hurd__
  21. #define PATH_MAX 4096
  22. #endif
  23. #include <locale.h>
  24. #include <pwd.h>
  25. #include <regex.h>
  26. #include <signal.h>
  27. #include <stdarg.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <time.h>
  32. #include <unistd.h>
  33. #include <wchar.h>
  34. #include <readline/readline.h>
  35. #ifndef __USE_XOPEN_EXTENDED
  36. #define __USE_XOPEN_EXTENDED 1
  37. #endif
  38. #include <ftw.h>
  39. #ifdef DEBUGMODE
  40. static int DEBUG_FD;
  41. static int
  42. xprintf(int fd, const char *fmt, ...)
  43. {
  44. char buf[BUFSIZ];
  45. int r;
  46. va_list ap;
  47. va_start(ap, fmt);
  48. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  49. if (r > 0)
  50. r = write(fd, buf, r);
  51. va_end(ap);
  52. return r;
  53. }
  54. static int enabledbg()
  55. {
  56. FILE *fp = fopen("/tmp/nnn_debug", "w");
  57. if (!fp) {
  58. fprintf(stderr, "Cannot open debug file\n");
  59. return -1;
  60. }
  61. DEBUG_FD = fileno(fp);
  62. if (DEBUG_FD == -1) {
  63. fprintf(stderr, "Cannot open debug file descriptor\n");
  64. return -1;
  65. }
  66. return 0;
  67. }
  68. static void disabledbg()
  69. {
  70. close(DEBUG_FD);
  71. }
  72. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  73. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  74. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  75. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=0x%p\n", x)
  76. #else
  77. #define DPRINTF_D(x)
  78. #define DPRINTF_U(x)
  79. #define DPRINTF_S(x)
  80. #define DPRINTF_P(x)
  81. #endif /* DEBUG */
  82. #define VERSION "v1.1"
  83. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  84. #undef MIN
  85. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  86. #define ISODD(x) ((x) & 1)
  87. #define CONTROL(c) ((c) ^ 0x40)
  88. #define TOUPPER(ch) \
  89. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  90. #define MAX_CMD_LEN 5120
  91. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  92. #define FILTER '/'
  93. #define MAX_BM 10
  94. struct assoc {
  95. char *regex; /* Regex to match on filename */
  96. char *mime; /* File type */
  97. };
  98. /* Supported actions */
  99. enum action {
  100. SEL_QUIT = 1,
  101. SEL_CDQUIT,
  102. SEL_BACK,
  103. SEL_GOIN,
  104. SEL_FLTR,
  105. SEL_MFLTR,
  106. SEL_SEARCH,
  107. SEL_NEXT,
  108. SEL_PREV,
  109. SEL_PGDN,
  110. SEL_PGUP,
  111. SEL_HOME,
  112. SEL_END,
  113. SEL_CD,
  114. SEL_CDHOME,
  115. SEL_CDBEGIN,
  116. SEL_CDLAST,
  117. SEL_CDBM,
  118. SEL_TOGGLEDOT,
  119. SEL_DETAIL,
  120. SEL_STATS,
  121. SEL_MEDIA,
  122. SEL_FMEDIA,
  123. SEL_DFB,
  124. SEL_FSIZE,
  125. SEL_BSIZE,
  126. SEL_MTIME,
  127. SEL_REDRAW,
  128. SEL_COPY,
  129. SEL_HELP,
  130. SEL_RUN,
  131. SEL_RUNARG,
  132. };
  133. struct key {
  134. int sym; /* Key pressed */
  135. enum action act; /* Action */
  136. char *run; /* Program to run */
  137. char *env; /* Environment variable to run */
  138. };
  139. #include "config.h"
  140. typedef struct entry {
  141. char name[NAME_MAX];
  142. mode_t mode;
  143. time_t t;
  144. off_t size;
  145. off_t bsize;
  146. } *pEntry;
  147. typedef struct {
  148. char *key;
  149. char *loc;
  150. } bm;
  151. typedef unsigned long ulong;
  152. /* Externs */
  153. #ifdef __APPLE__
  154. extern int add_history(const char *string);
  155. #else
  156. extern void add_history(const char *string);
  157. #endif
  158. extern int wget_wch(WINDOW *win, wint_t *wch);
  159. /* Global context */
  160. static struct entry *dents;
  161. static int ndents, cur, total_dents;
  162. static int idle;
  163. static char *player;
  164. static char *copier;
  165. static char *editor;
  166. static char *desktop_manager;
  167. static off_t blk_size;
  168. static size_t fs_free;
  169. static int open_max;
  170. static bm bookmark[MAX_BM];
  171. static const double div_2_pow_10 = 1.0 / 1024.0;
  172. static char *utils[] = {
  173. #ifdef __APPLE__
  174. "/usr/bin/open",
  175. #else
  176. "/usr/bin/xdg-open",
  177. #endif
  178. "nlay"
  179. };
  180. /* For use in functions which are isolated and don't return the buffer */
  181. static char g_buf[MAX_CMD_LEN];
  182. /*
  183. * Layout:
  184. * .---------
  185. * | cwd: /mnt/path
  186. * |
  187. * | file0
  188. * | file1
  189. * | > file2
  190. * | file3
  191. * | file4
  192. * ...
  193. * | filen
  194. * |
  195. * | Permission denied
  196. * '------
  197. */
  198. static void printmsg(char *);
  199. static void printwarn(void);
  200. static void printerr(int, char *);
  201. static void redraw(char *path);
  202. static rlim_t
  203. max_openfds()
  204. {
  205. struct rlimit rl;
  206. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  207. if (limit != 0)
  208. return 32;
  209. limit = rl.rlim_cur;
  210. rl.rlim_cur = rl.rlim_max;
  211. if (setrlimit(RLIMIT_NOFILE, &rl) == 0)
  212. return rl.rlim_max - 64;
  213. if (limit > 128)
  214. return limit - 64;
  215. return 32;
  216. }
  217. /* Just a safe strncpy(3) */
  218. static void
  219. xstrlcpy(char *dest, const char *src, size_t n)
  220. {
  221. while (--n && (*dest = *src))
  222. ++dest, ++src;
  223. if (!n)
  224. *dest = '\0';
  225. }
  226. /*
  227. * The poor man's implementation of memrchr(3).
  228. * We are only looking for '/' in this program.
  229. */
  230. static void *
  231. xmemrchr(const void *s, unsigned char ch, size_t n)
  232. {
  233. static unsigned char *p;
  234. if (!s || !n)
  235. return NULL;
  236. p = (unsigned char *)s + n - 1;
  237. while (n) {
  238. if (*p == ch)
  239. return p;
  240. --p;
  241. --n;
  242. }
  243. return NULL;
  244. }
  245. /*
  246. * The following dirname(3) implementation does not
  247. * modify the input. We use a copy of the original.
  248. *
  249. * Modified from the glibc (GNU LGPL) version.
  250. */
  251. static char *
  252. xdirname(const char *path)
  253. {
  254. static char buf[PATH_MAX];
  255. static char *last_slash;
  256. xstrlcpy(buf, path, PATH_MAX);
  257. /* Find last '/'. */
  258. last_slash = strrchr(buf, '/');
  259. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  260. /* Determine whether all remaining characters are slashes. */
  261. char *runp;
  262. for (runp = last_slash; runp != buf; --runp)
  263. if (runp[-1] != '/')
  264. break;
  265. /* The '/' is the last character, we have to look further. */
  266. if (runp != buf)
  267. last_slash = xmemrchr(buf, '/', runp - buf);
  268. }
  269. if (last_slash != NULL) {
  270. /* Determine whether all remaining characters are slashes. */
  271. char *runp;
  272. for (runp = last_slash; runp != buf; --runp)
  273. if (runp[-1] != '/')
  274. break;
  275. /* Terminate the buffer. */
  276. if (runp == buf) {
  277. /* The last slash is the first character in the string.
  278. * We have to return "/". As a special case we have to
  279. * return "//" if there are exactly two slashes at the
  280. * beginning of the string. See XBD 4.10 Path Name
  281. * Resolution for more information.
  282. */
  283. if (last_slash == buf + 1)
  284. ++last_slash;
  285. else
  286. last_slash = buf + 1;
  287. } else
  288. last_slash = runp;
  289. last_slash[0] = '\0';
  290. } else {
  291. /* This assignment is ill-designed but the XPG specs require to
  292. * return a string containing "." in any case no directory part
  293. * is found and so a static and constant string is required.
  294. */
  295. buf[0] = '.';
  296. buf[1] = '\0';
  297. }
  298. return buf;
  299. }
  300. /*
  301. * Return number of dots of all chars in a string are dots, else 0
  302. */
  303. static int
  304. all_dots(const char *ptr)
  305. {
  306. if (!ptr)
  307. return FALSE;
  308. int count = 0;
  309. while (*ptr == '.')
  310. ++count, ++ptr;
  311. if (*ptr)
  312. return 0;
  313. return count;
  314. }
  315. static void
  316. initcurses(void)
  317. {
  318. if (initscr() == NULL) {
  319. char *term = getenv("TERM");
  320. if (term != NULL)
  321. fprintf(stderr, "error opening terminal: %s\n", term);
  322. else
  323. fprintf(stderr, "failed to initialize curses\n");
  324. exit(1);
  325. }
  326. cbreak();
  327. noecho();
  328. nonl();
  329. intrflush(stdscr, FALSE);
  330. keypad(stdscr, TRUE);
  331. curs_set(FALSE); /* Hide cursor */
  332. start_color();
  333. use_default_colors();
  334. timeout(1000); /* One second */
  335. }
  336. static void
  337. exitcurses(void)
  338. {
  339. endwin(); /* Restore terminal */
  340. }
  341. /*
  342. * Spawns a child process. Behaviour can be controlled using flag:
  343. * Limited to 2 arguments to a program
  344. * flag works on bit set:
  345. * - 0b1: draw a marker to indicate nnn spawned e.g., a shell
  346. * - 0b10: do not wait in parent for child process e.g. DE file manager
  347. * - 0b100: suppress stdout and stderr
  348. * - 0b1000: restore default SIGINT handler
  349. * - 0b10000000: exit curses mode
  350. */
  351. static void
  352. spawn(char *file, char *arg1, char *arg2, char *dir, unsigned char flag)
  353. {
  354. pid_t pid;
  355. int status;
  356. if (flag & 0b10000000)
  357. exitcurses();
  358. pid = fork();
  359. if (pid == 0) {
  360. if (dir != NULL)
  361. status = chdir(dir);
  362. /* Show a marker (to indicate nnn spawned shell) */
  363. if (flag & 0b1)
  364. printf("\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  365. /* Suppress stdout and stderr */
  366. if (flag & 0b100) {
  367. int fd = open("/dev/null", O_WRONLY, 0200);
  368. dup2(fd, 1);
  369. dup2(fd, 2);
  370. close(fd);
  371. }
  372. if (flag & 0b1000)
  373. signal(SIGINT, SIG_DFL);
  374. execlp(file, file, arg1, arg2, NULL);
  375. _exit(1);
  376. } else {
  377. if (!(flag & 0b10))
  378. /* Ignore interruptions */
  379. while (waitpid(pid, &status, 0) == -1)
  380. DPRINTF_D(status);
  381. DPRINTF_D(pid);
  382. if (flag & 0b10000000)
  383. initcurses();
  384. }
  385. }
  386. static char *
  387. xgetenv(char *name, char *fallback)
  388. {
  389. char *value;
  390. if (name == NULL)
  391. return fallback;
  392. value = getenv(name);
  393. return value && value[0] ? value : fallback;
  394. }
  395. /*
  396. * We assume none of the strings are NULL.
  397. *
  398. * Let's have the logic to sort numeric names in numeric order.
  399. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  400. *
  401. * If the absolute numeric values are same, we fallback to alphasort.
  402. */
  403. static int
  404. xstricmp(char *s1, char *s2)
  405. {
  406. static char *c1, *c2;
  407. c1 = s1;
  408. while (isspace(*c1))
  409. ++c1;
  410. if (*c1 == '-' || *c1 == '+')
  411. ++c1;
  412. while (*c1 >= '0' && *c1 <= '9')
  413. ++c1;
  414. c2 = s2;
  415. while (isspace(*c2))
  416. ++c2;
  417. if (*c2 == '-' || *c2 == '+')
  418. ++c2;
  419. while (*c2 >= '0' && *c2 <= '9')
  420. ++c2;
  421. if (*c1 == '\0' && *c2 == '\0') {
  422. static long long num1, num2;
  423. num1 = strtoll(s1, &c1, 10);
  424. num2 = strtoll(s2, &c2, 10);
  425. if (num1 != num2) {
  426. if (num1 > num2)
  427. return 1;
  428. else
  429. return -1;
  430. }
  431. } else if (*c1 == '\0' && *c2 != '\0')
  432. return -1;
  433. else if (*c1 != '\0' && *c2 == '\0')
  434. return 1;
  435. while (*s2 && *s1 && TOUPPER(*s1) == TOUPPER(*s2))
  436. ++s1, ++s2;
  437. /* In case of alphabetically same names, make sure
  438. * lower case one comes before upper case one
  439. */
  440. if (!*s1 && !*s2)
  441. return 1;
  442. return (int) (TOUPPER(*s1) - TOUPPER(*s2));
  443. }
  444. /* Trim all whitespace from both ends, / from end */
  445. static char *
  446. strstrip(char *s)
  447. {
  448. if (!s || !*s)
  449. return s;
  450. size_t len = strlen(s) - 1;
  451. while (len != 0 && (isspace(s[len]) || s[len] == '/'))
  452. --len;
  453. s[len + 1] = '\0';
  454. while (*s && isspace(*s))
  455. ++s;
  456. return s;
  457. }
  458. static char *
  459. getmime(char *file)
  460. {
  461. regex_t regex;
  462. unsigned int i;
  463. static unsigned int len = LEN(assocs);
  464. for (i = 0; i < len; ++i) {
  465. if (regcomp(&regex, assocs[i].regex,
  466. REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  467. continue;
  468. if (regexec(&regex, file, 0, NULL, 0) == 0)
  469. return assocs[i].mime;
  470. }
  471. return NULL;
  472. }
  473. static int
  474. setfilter(regex_t *regex, char *filter)
  475. {
  476. static size_t len;
  477. static int r;
  478. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  479. if (r != 0 && filter && filter[0] != '\0') {
  480. len = COLS;
  481. if (len > LINE_MAX)
  482. len = LINE_MAX;
  483. regerror(r, regex, g_buf, len);
  484. printmsg(g_buf);
  485. }
  486. return r;
  487. }
  488. static void
  489. initfilter(int dot, char **ifilter)
  490. {
  491. *ifilter = dot ? "." : "^[^.]";
  492. }
  493. static int
  494. visible(regex_t *regex, char *file)
  495. {
  496. return regexec(regex, file, 0, NULL, 0) == 0;
  497. }
  498. static int
  499. entrycmp(const void *va, const void *vb)
  500. {
  501. static pEntry pa, pb;
  502. pa = (pEntry)va;
  503. pb = (pEntry)vb;
  504. /* Sort directories first */
  505. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  506. return 1;
  507. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  508. return -1;
  509. /* Do the actual sorting */
  510. if (mtimeorder)
  511. return pb->t - pa->t;
  512. if (sizeorder) {
  513. if (pb->size > pa->size)
  514. return 1;
  515. else if (pb->size < pa->size)
  516. return -1;
  517. }
  518. if (bsizeorder) {
  519. if (pb->bsize > pa->bsize)
  520. return 1;
  521. else if (pb->bsize < pa->bsize)
  522. return -1;
  523. }
  524. return xstricmp(pa->name, pb->name);
  525. }
  526. /* Messages show up at the bottom */
  527. static void
  528. printmsg(char *msg)
  529. {
  530. move(LINES - 1, 0);
  531. printw("%s\n", msg);
  532. }
  533. /* Display warning as a message */
  534. static void
  535. printwarn(void)
  536. {
  537. printmsg(strerror(errno));
  538. }
  539. /* Kill curses and display error before exiting */
  540. static void
  541. printerr(int ret, char *prefix)
  542. {
  543. exitcurses();
  544. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  545. exit(ret);
  546. }
  547. /* Clear the last line */
  548. static void
  549. clearprompt(void)
  550. {
  551. printmsg("");
  552. }
  553. /* Print prompt on the last line */
  554. static void
  555. printprompt(char *str)
  556. {
  557. clearprompt();
  558. printw(str);
  559. }
  560. /* Returns SEL_* if key is bound and 0 otherwise.
  561. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  562. * The next keyboard input can be simulated by presel.
  563. */
  564. static int
  565. nextsel(char **run, char **env, int *presel)
  566. {
  567. int c = *presel;
  568. unsigned int i;
  569. static unsigned int len = LEN(bindings);
  570. if (c == 0)
  571. c = getch();
  572. else
  573. *presel = 0;
  574. if (c == -1)
  575. ++idle;
  576. else
  577. idle = 0;
  578. for (i = 0; i < len; ++i)
  579. if (c == bindings[i].sym) {
  580. *run = bindings[i].run;
  581. *env = bindings[i].env;
  582. return bindings[i].act;
  583. }
  584. return 0;
  585. }
  586. /*
  587. * Move non-matching entries to the end
  588. */
  589. static void
  590. fill(struct entry **dents,
  591. int (*filter)(regex_t *, char *), regex_t *re)
  592. {
  593. static int count;
  594. for (count = 0; count < ndents; ++count) {
  595. if (filter(re, (*dents)[count].name) == 0) {
  596. if (count != --ndents) {
  597. static struct entry _dent;
  598. /* Copy count to tmp */
  599. xstrlcpy(_dent.name, (*dents)[count].name,
  600. NAME_MAX);
  601. _dent.mode = (*dents)[count].mode;
  602. _dent.t = (*dents)[count].t;
  603. _dent.size = (*dents)[count].size;
  604. _dent.bsize = (*dents)[count].bsize;
  605. /* Copy ndents - 1 to count */
  606. xstrlcpy((*dents)[count].name,
  607. (*dents)[ndents].name, NAME_MAX);
  608. (*dents)[count].mode = (*dents)[ndents].mode;
  609. (*dents)[count].t = (*dents)[ndents].t;
  610. (*dents)[count].size = (*dents)[ndents].size;
  611. (*dents)[count].bsize = (*dents)[ndents].bsize;
  612. /* Copy tmp to ndents - 1 */
  613. xstrlcpy((*dents)[ndents].name, _dent.name,
  614. NAME_MAX);
  615. (*dents)[ndents].mode = _dent.mode;
  616. (*dents)[ndents].t = _dent.t;
  617. (*dents)[ndents].size = _dent.size;
  618. (*dents)[ndents].bsize = _dent.bsize;
  619. --count;
  620. }
  621. continue;
  622. }
  623. }
  624. }
  625. static int
  626. matches(char *fltr)
  627. {
  628. static regex_t re;
  629. /* Search filter */
  630. if (setfilter(&re, fltr) != 0)
  631. return -1;
  632. fill(&dents, visible, &re);
  633. qsort(dents, ndents, sizeof(*dents), entrycmp);
  634. return 0;
  635. }
  636. static int
  637. readln(char *path)
  638. {
  639. static char ln[LINE_MAX << 2];
  640. static wchar_t wln[LINE_MAX];
  641. static wint_t ch[2] = {0};
  642. int r, total = ndents;
  643. int oldcur = cur;
  644. int len = 1;
  645. char *pln = ln + 1;
  646. memset(wln, 0, LINE_MAX << 2);
  647. wln[0] = FILTER;
  648. ln[0] = FILTER;
  649. ln[1] = '\0';
  650. cur = 0;
  651. timeout(-1);
  652. echo();
  653. curs_set(TRUE);
  654. printprompt(ln);
  655. while ((r = wget_wch(stdscr, ch)) != ERR) {
  656. if (r == OK) {
  657. switch (*ch) {
  658. case '\r': // with nonl(), this is ENTER key value
  659. if (len == 1) {
  660. cur = oldcur;
  661. goto end;
  662. }
  663. if (matches(pln) == -1)
  664. goto end;
  665. redraw(path);
  666. goto end;
  667. case 127: // handle DEL
  668. if (len == 1) {
  669. cur = oldcur;
  670. *ch = CONTROL('L');
  671. goto end;
  672. }
  673. if (len == 2)
  674. cur = oldcur;
  675. wln[--len] = '\0';
  676. wcstombs(ln, wln, LINE_MAX << 2);
  677. ndents = total;
  678. if (matches(pln) == -1) {
  679. printprompt(ln);
  680. continue;
  681. }
  682. redraw(path);
  683. printprompt(ln);
  684. break;
  685. case CONTROL('L'):
  686. if (len == 1)
  687. cur = oldcur; // fallthrough
  688. case CONTROL('Q'):
  689. goto end;
  690. default:
  691. wln[len] = (wchar_t)*ch;
  692. ++len;
  693. wln[len] = '\0';
  694. wcstombs(ln, wln, LINE_MAX << 2);
  695. ndents = total;
  696. if (matches(pln) == -1)
  697. continue;
  698. redraw(path);
  699. printprompt(ln);
  700. }
  701. } else {
  702. switch (*ch) {
  703. case KEY_DC: // fallthrough
  704. case KEY_BACKSPACE:
  705. if (len == 1) {
  706. cur = oldcur;
  707. *ch = CONTROL('L');
  708. goto end;
  709. }
  710. if (len == 2)
  711. cur = oldcur;
  712. wln[--len] = '\0';
  713. wcstombs(ln, wln, LINE_MAX << 2);
  714. ndents = total;
  715. if (matches(pln) == -1)
  716. continue;
  717. redraw(path);
  718. printprompt(ln);
  719. break;
  720. case KEY_DOWN: // fallthrough
  721. case KEY_UP: // fallthrough
  722. case KEY_LEFT: // fallthrough
  723. case KEY_RIGHT:
  724. if (len == 1)
  725. cur = oldcur; // fallthrough
  726. default:
  727. goto end;
  728. }
  729. }
  730. }
  731. end:
  732. noecho();
  733. curs_set(FALSE);
  734. timeout(1000);
  735. /* Return keys for navigation etc. */
  736. return *ch;
  737. }
  738. static int
  739. canopendir(char *path)
  740. {
  741. static DIR *dirp;
  742. dirp = opendir(path);
  743. if (dirp == NULL)
  744. return 0;
  745. closedir(dirp);
  746. return 1;
  747. }
  748. /*
  749. * Returns "dir/name or "/name"
  750. */
  751. static char *
  752. mkpath(char *dir, char *name, char *out, size_t n)
  753. {
  754. /* Handle absolute path */
  755. if (name[0] == '/')
  756. xstrlcpy(out, name, n);
  757. else {
  758. /* Handle root case */
  759. if (strcmp(dir, "/") == 0)
  760. snprintf(out, n, "/%s", name);
  761. else
  762. snprintf(out, n, "%s/%s", dir, name);
  763. }
  764. return out;
  765. }
  766. static void
  767. parsebmstr(char *bms)
  768. {
  769. int i = 0;
  770. while (*bms && i < MAX_BM) {
  771. bookmark[i].key = bms;
  772. ++bms;
  773. while (*bms && *bms != ':')
  774. ++bms;
  775. if (!*bms) {
  776. bookmark[i].key = NULL;
  777. break;
  778. }
  779. *bms = '\0';
  780. bookmark[i].loc = ++bms;
  781. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  782. bookmark[i].key = NULL;
  783. break;
  784. }
  785. while (*bms && *bms != ';')
  786. ++bms;
  787. if (*bms)
  788. *bms = '\0';
  789. else
  790. break;
  791. ++bms;
  792. ++i;
  793. }
  794. }
  795. static char *
  796. readinput(void)
  797. {
  798. timeout(-1);
  799. echo();
  800. curs_set(TRUE);
  801. memset(g_buf, 0, LINE_MAX);
  802. wgetnstr(stdscr, g_buf, LINE_MAX - 1);
  803. noecho();
  804. curs_set(FALSE);
  805. timeout(1000);
  806. return g_buf[0] ? g_buf : NULL;
  807. }
  808. static char *
  809. replace_escape(const char *str)
  810. {
  811. static char buffer[PATH_MAX];
  812. static wchar_t wbuf[PATH_MAX];
  813. static wchar_t *buf;
  814. buffer[0] = '\0';
  815. buf = wbuf;
  816. /* Convert multi-byte to wide char */
  817. mbstowcs(wbuf, str, PATH_MAX);
  818. while (*buf) {
  819. if (*buf <= '\x1f' || *buf == '\x7f')
  820. *buf = '\?';
  821. ++buf;
  822. }
  823. /* Convert wide char to multi-byte */
  824. wcstombs(buffer, wbuf, PATH_MAX);
  825. return buffer;
  826. }
  827. static void
  828. printent(struct entry *ent, int sel)
  829. {
  830. static int ncols;
  831. if (PATH_MAX + 16 < COLS)
  832. ncols = PATH_MAX + 16;
  833. else
  834. ncols = COLS;
  835. if (S_ISDIR(ent->mode))
  836. snprintf(g_buf, ncols, "%s%s/", CURSYM(sel),
  837. replace_escape(ent->name));
  838. else if (S_ISLNK(ent->mode))
  839. snprintf(g_buf, ncols, "%s%s@", CURSYM(sel),
  840. replace_escape(ent->name));
  841. else if (S_ISSOCK(ent->mode))
  842. snprintf(g_buf, ncols, "%s%s=", CURSYM(sel),
  843. replace_escape(ent->name));
  844. else if (S_ISFIFO(ent->mode))
  845. snprintf(g_buf, ncols, "%s%s|", CURSYM(sel),
  846. replace_escape(ent->name));
  847. else if (ent->mode & 0100)
  848. snprintf(g_buf, ncols, "%s%s*", CURSYM(sel),
  849. replace_escape(ent->name));
  850. else
  851. snprintf(g_buf, ncols, "%s%s", CURSYM(sel),
  852. replace_escape(ent->name));
  853. printw("%s\n", g_buf);
  854. }
  855. static char*
  856. coolsize(off_t size)
  857. {
  858. static const char * const U[]
  859. = {"B", "K", "M", "G", "T", "P", "E", "Z", "Y"};
  860. static char size_buf[12]; /* Buffer to hold human readable size */
  861. static int i;
  862. static off_t tmp;
  863. static long double rem;
  864. i = 0;
  865. rem = 0;
  866. while (size > 1024) {
  867. tmp = size;
  868. size >>= 10;
  869. rem = tmp - (size << 10);
  870. ++i;
  871. }
  872. snprintf(size_buf, 12, "%.*Lf%s", i, size + rem * div_2_pow_10, U[i]);
  873. return size_buf;
  874. }
  875. static void
  876. printent_long(struct entry *ent, int sel)
  877. {
  878. static int ncols;
  879. static char buf[18];
  880. if (PATH_MAX + 32 < COLS)
  881. ncols = PATH_MAX + 32;
  882. else
  883. ncols = COLS;
  884. strftime(buf, 18, "%d %m %Y %H:%M", localtime(&ent->t));
  885. if (sel)
  886. attron(A_REVERSE);
  887. if (!bsizeorder) {
  888. if (S_ISDIR(ent->mode))
  889. snprintf(g_buf, ncols, "%s%-16.16s / %s/",
  890. CURSYM(sel), buf, replace_escape(ent->name));
  891. else if (S_ISLNK(ent->mode))
  892. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  893. CURSYM(sel), buf, replace_escape(ent->name));
  894. else if (S_ISSOCK(ent->mode))
  895. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  896. CURSYM(sel), buf, replace_escape(ent->name));
  897. else if (S_ISFIFO(ent->mode))
  898. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  899. CURSYM(sel), buf, replace_escape(ent->name));
  900. else if (S_ISBLK(ent->mode))
  901. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  902. CURSYM(sel), buf, replace_escape(ent->name));
  903. else if (S_ISCHR(ent->mode))
  904. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  905. CURSYM(sel), buf, replace_escape(ent->name));
  906. else if (ent->mode & 0100)
  907. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  908. CURSYM(sel), buf, coolsize(ent->size),
  909. replace_escape(ent->name));
  910. else
  911. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  912. CURSYM(sel), buf, coolsize(ent->size),
  913. replace_escape(ent->name));
  914. } else {
  915. if (S_ISDIR(ent->mode))
  916. snprintf(g_buf, ncols, "%s%-16.16s %8.8s/ %s/",
  917. CURSYM(sel), buf, coolsize(ent->bsize << 9),
  918. replace_escape(ent->name));
  919. else if (S_ISLNK(ent->mode))
  920. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  921. CURSYM(sel), buf,
  922. replace_escape(ent->name));
  923. else if (S_ISSOCK(ent->mode))
  924. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  925. CURSYM(sel), buf,
  926. replace_escape(ent->name));
  927. else if (S_ISFIFO(ent->mode))
  928. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  929. CURSYM(sel), buf,
  930. replace_escape(ent->name));
  931. else if (S_ISBLK(ent->mode))
  932. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  933. CURSYM(sel), buf,
  934. replace_escape(ent->name));
  935. else if (S_ISCHR(ent->mode))
  936. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  937. CURSYM(sel), buf,
  938. replace_escape(ent->name));
  939. else if (ent->mode & 0100)
  940. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  941. CURSYM(sel), buf, coolsize(ent->bsize << 9),
  942. replace_escape(ent->name));
  943. else
  944. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  945. CURSYM(sel), buf, coolsize(ent->bsize << 9),
  946. replace_escape(ent->name));
  947. }
  948. printw("%s\n", g_buf);
  949. if (sel)
  950. attroff(A_REVERSE);
  951. }
  952. static void (*printptr)(struct entry *ent, int sel) = &printent_long;
  953. static char
  954. get_fileind(mode_t mode, char *desc)
  955. {
  956. static char c;
  957. if (S_ISREG(mode)) {
  958. c = '-';
  959. sprintf(desc, "%s", "regular file");
  960. if (mode & 0100)
  961. strcat(desc, ", executable");
  962. } else if (S_ISDIR(mode)) {
  963. c = 'd';
  964. sprintf(desc, "%s", "directory");
  965. } else if (S_ISBLK(mode)) {
  966. c = 'b';
  967. sprintf(desc, "%s", "block special device");
  968. } else if (S_ISCHR(mode)) {
  969. c = 'c';
  970. sprintf(desc, "%s", "character special device");
  971. #ifdef S_ISFIFO
  972. } else if (S_ISFIFO(mode)) {
  973. c = 'p';
  974. sprintf(desc, "%s", "FIFO");
  975. #endif /* S_ISFIFO */
  976. #ifdef S_ISLNK
  977. } else if (S_ISLNK(mode)) {
  978. c = 'l';
  979. sprintf(desc, "%s", "symbolic link");
  980. #endif /* S_ISLNK */
  981. #ifdef S_ISSOCK
  982. } else if (S_ISSOCK(mode)) {
  983. c = 's';
  984. sprintf(desc, "%s", "socket");
  985. #endif /* S_ISSOCK */
  986. #ifdef S_ISDOOR
  987. /* Solaris 2.6, etc. */
  988. } else if (S_ISDOOR(mode)) {
  989. c = 'D';
  990. desc[0] = '\0';
  991. #endif /* S_ISDOOR */
  992. } else {
  993. /* Unknown type -- possibly a regular file? */
  994. c = '?';
  995. desc[0] = '\0';
  996. }
  997. return c;
  998. }
  999. /* Convert a mode field into "ls -l" type perms field. */
  1000. static char *
  1001. get_lsperms(mode_t mode, char *desc)
  1002. {
  1003. static const char * const rwx[] = {"---", "--x", "-w-", "-wx",
  1004. "r--", "r-x", "rw-", "rwx"};
  1005. static char bits[11];
  1006. bits[0] = get_fileind(mode, desc);
  1007. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  1008. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  1009. strcpy(&bits[7], rwx[(mode & 7)]);
  1010. if (mode & S_ISUID)
  1011. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1012. if (mode & S_ISGID)
  1013. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1014. if (mode & S_ISVTX)
  1015. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1016. bits[10] = '\0';
  1017. return bits;
  1018. }
  1019. /*
  1020. * Gets only a single line (that's what we need
  1021. * for now) or shows full command output in pager.
  1022. *
  1023. * If pager is valid, returns NULL
  1024. */
  1025. static char *
  1026. get_output(char *buf, size_t bytes, char *file,
  1027. char *arg1, char *arg2, int pager)
  1028. {
  1029. pid_t pid;
  1030. int pipefd[2];
  1031. FILE *pf;
  1032. int status;
  1033. char *ret = NULL;
  1034. if (pipe(pipefd) == -1)
  1035. printerr(1, "pipe(2)");
  1036. pid = fork();
  1037. if (pid == 0) {
  1038. /* In child */
  1039. close(pipefd[0]);
  1040. dup2(pipefd[1], STDOUT_FILENO);
  1041. dup2(pipefd[1], STDERR_FILENO);
  1042. execlp(file, file, arg1, arg2, NULL);
  1043. _exit(1);
  1044. }
  1045. /* In parent */
  1046. waitpid(pid, &status, 0);
  1047. close(pipefd[1]);
  1048. if (!pager) {
  1049. pf = fdopen(pipefd[0], "r");
  1050. if (pf) {
  1051. ret = fgets(buf, bytes, pf);
  1052. close(pipefd[0]);
  1053. }
  1054. return ret;
  1055. }
  1056. pid = fork();
  1057. if (pid == 0) {
  1058. /* Show in pager in child */
  1059. dup2(pipefd[0], STDIN_FILENO);
  1060. execlp("less", "less", NULL);
  1061. close(pipefd[0]);
  1062. _exit(1);
  1063. }
  1064. /* In parent */
  1065. waitpid(pid, &status, 0);
  1066. return NULL;
  1067. }
  1068. /*
  1069. * Follows the stat(1) output closely
  1070. */
  1071. static int
  1072. show_stats(char *fpath, char *fname, struct stat *sb)
  1073. {
  1074. char *perms = get_lsperms(sb->st_mode, g_buf);
  1075. char *p, *begin = g_buf;
  1076. char tmp[] = "/tmp/nnnXXXXXX";
  1077. int fd = mkstemp(tmp);
  1078. if (fd == -1)
  1079. return -1;
  1080. /* Show file name or 'symlink' -> 'target' */
  1081. if (perms[0] == 'l') {
  1082. /* Note that MAX_CMD_LEN > PATH_MAX */
  1083. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1084. if (len != -1) {
  1085. g_buf[len] = '\0';
  1086. dprintf(fd, " File: '%s' -> ",
  1087. replace_escape(fname));
  1088. dprintf(fd, "'%s'",
  1089. replace_escape(g_buf));
  1090. }
  1091. } else
  1092. dprintf(fd, " File: '%s'", replace_escape(fname));
  1093. /* Show size, blocks, file type */
  1094. #ifdef __APPLE__
  1095. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1096. #else
  1097. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1098. #endif
  1099. sb->st_size, sb->st_blocks, sb->st_blksize, g_buf);
  1100. /* Show containing device, inode, hardlink count */
  1101. #ifdef __APPLE__
  1102. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1103. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1104. #else
  1105. sprintf(g_buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  1106. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1107. #endif
  1108. g_buf, sb->st_ino, sb->st_nlink);
  1109. /* Show major, minor number for block or char device */
  1110. if (perms[0] == 'b' || perms[0] == 'c')
  1111. dprintf(fd, " Device type: %x,%x",
  1112. major(sb->st_rdev), minor(sb->st_rdev));
  1113. /* Show permissions, owner, group */
  1114. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)",
  1115. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7, sb->st_mode & 7,
  1116. perms,
  1117. sb->st_uid, (getpwuid(sb->st_uid))->pw_name,
  1118. sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1119. /* Show last access time */
  1120. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1121. dprintf(fd, "\n\n Access: %s", g_buf);
  1122. /* Show last modification time */
  1123. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1124. dprintf(fd, "\n Modify: %s", g_buf);
  1125. /* Show last status change time */
  1126. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1127. dprintf(fd, "\n Change: %s", g_buf);
  1128. if (S_ISREG(sb->st_mode)) {
  1129. /* Show file(1) output */
  1130. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1131. if (p) {
  1132. dprintf(fd, "\n\n ");
  1133. while (*p) {
  1134. if (*p == ',') {
  1135. *p = '\0';
  1136. dprintf(fd, " %s\n", begin);
  1137. begin = p + 1;
  1138. }
  1139. ++p;
  1140. }
  1141. dprintf(fd, " %s", begin);
  1142. }
  1143. dprintf(fd, "\n\n");
  1144. } else
  1145. dprintf(fd, "\n\n\n");
  1146. close(fd);
  1147. exitcurses();
  1148. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1149. unlink(tmp);
  1150. initcurses();
  1151. return 0;
  1152. }
  1153. static int
  1154. show_mediainfo(char *fpath, char *arg)
  1155. {
  1156. if (!get_output(g_buf, MAX_CMD_LEN, "which", "mediainfo", NULL, 0))
  1157. return -1;
  1158. exitcurses();
  1159. get_output(NULL, 0, "mediainfo", fpath, arg, 1);
  1160. initcurses();
  1161. return 0;
  1162. }
  1163. static int
  1164. show_help(void)
  1165. {
  1166. char tmp[] = "/tmp/nnnXXXXXX";
  1167. static char helpstr[] = ("\
  1168. Key | Function\n\
  1169. -+-\n\
  1170. Up, k, ^P | Previous entry\n\
  1171. Down, j, ^N | Next entry\n\
  1172. PgUp, ^U | Scroll half page up\n\
  1173. PgDn, ^D | Scroll half page down\n\
  1174. Home, g, ^, ^A | Jump to first entry\n\
  1175. End, G, $, ^E | Jump to last entry\n\
  1176. Right, Enter, l, ^M | Open file or enter dir\n\
  1177. Left, Bksp, h, ^H | Go to parent dir\n\
  1178. Insert | Toggle navigate-as-you-type mode\n\
  1179. ~ | Jump to HOME dir\n\
  1180. & | Jump to initial dir\n\
  1181. - | Jump to last visited dir\n\
  1182. / | Filter dir contents\n\
  1183. ^/ | Search dir in desktop search tool\n\
  1184. . | Toggle hide .dot files\n\
  1185. b | Show bookmark key prompt\n\
  1186. c | Show change dir prompt\n\
  1187. d | Toggle detail view\n\
  1188. D | Toggle current file details screen\n\
  1189. m | Show concise mediainfo\n\
  1190. M | Show full mediainfo\n\
  1191. s | Toggle sort by file size\n\
  1192. S | Toggle disk usage analyzer mode\n\
  1193. t | Toggle sort by modified time\n\
  1194. ! | Spawn SHELL in PWD (fallback sh)\n\
  1195. e | Edit entry in EDITOR (fallback vi)\n\
  1196. o | Open dir in NNN_DE_FILE_MANAGER\n\
  1197. p | Open entry in PAGER (fallback less)\n\
  1198. ^K | Invoke file path copier\n\
  1199. ^L | Force a redraw, exit filter prompt\n\
  1200. ? | Toggle help and settings screen\n\
  1201. Q | Quit and change directory\n\
  1202. q, ^Q | Quit\n\n\n");
  1203. int i = 0, fd = mkstemp(tmp);
  1204. if (fd == -1)
  1205. return -1;
  1206. dprintf(fd, "%s", helpstr);
  1207. if (getenv("NNN_BMS")) {
  1208. dprintf(fd, "BOOKMARKS\n");
  1209. for (; i < MAX_BM; ++i)
  1210. if (bookmark[i].key)
  1211. dprintf(fd, " %s: %s\n",
  1212. bookmark[i].key, bookmark[i].loc);
  1213. else
  1214. break;
  1215. dprintf(fd, "\n");
  1216. }
  1217. if (editor)
  1218. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1219. if (desktop_manager)
  1220. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1221. if (idletimeout)
  1222. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1223. if (copier)
  1224. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1225. dprintf(fd, "\n");
  1226. close(fd);
  1227. exitcurses();
  1228. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1229. unlink(tmp);
  1230. initcurses();
  1231. return 0;
  1232. }
  1233. static int
  1234. sum_bsizes(const char *fpath, const struct stat *sb,
  1235. int typeflag, struct FTW *ftwbuf)
  1236. {
  1237. if (typeflag == FTW_F || typeflag == FTW_D)
  1238. blk_size += sb->st_blocks;
  1239. return 0;
  1240. }
  1241. static int
  1242. getorder(size_t size)
  1243. {
  1244. switch (size) {
  1245. case 4096:
  1246. return 12;
  1247. case 512:
  1248. return 9;
  1249. case 8192:
  1250. return 13;
  1251. case 16384:
  1252. return 14;
  1253. case 32768:
  1254. return 15;
  1255. case 65536:
  1256. return 16;
  1257. case 131072:
  1258. return 17;
  1259. case 262144:
  1260. return 18;
  1261. case 524288:
  1262. return 19;
  1263. case 1048576:
  1264. return 20;
  1265. case 2048:
  1266. return 11;
  1267. case 1024:
  1268. return 10;
  1269. default:
  1270. return 0;
  1271. }
  1272. }
  1273. static int
  1274. dentfill(char *path, struct entry **dents,
  1275. int (*filter)(regex_t *, char *), regex_t *re)
  1276. {
  1277. static char newpath[PATH_MAX];
  1278. static DIR *dirp;
  1279. static struct dirent *dp;
  1280. static struct stat sb;
  1281. static int n;
  1282. n = 0;
  1283. dirp = opendir(path);
  1284. if (dirp == NULL)
  1285. return 0;
  1286. while ((dp = readdir(dirp)) != NULL) {
  1287. /* Skip self and parent */
  1288. if ((dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
  1289. (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))))
  1290. continue;
  1291. if (filter(re, dp->d_name) == 0)
  1292. continue;
  1293. if (n == total_dents) {
  1294. total_dents += 64;
  1295. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1296. if (*dents == NULL)
  1297. printerr(1, "realloc");
  1298. }
  1299. xstrlcpy((*dents)[n].name, dp->d_name, NAME_MAX);
  1300. /* Get mode flags */
  1301. mkpath(path, dp->d_name, newpath, PATH_MAX);
  1302. if (lstat(newpath, &sb) == -1) {
  1303. if (*dents)
  1304. free(*dents);
  1305. printerr(1, "lstat");
  1306. }
  1307. (*dents)[n].mode = sb.st_mode;
  1308. (*dents)[n].t = sb.st_mtime;
  1309. (*dents)[n].size = sb.st_size;
  1310. if (bsizeorder) {
  1311. if (S_ISDIR(sb.st_mode)) {
  1312. blk_size = 0;
  1313. if (nftw(newpath, sum_bsizes, open_max,
  1314. FTW_MOUNT | FTW_PHYS) == -1) {
  1315. printmsg("nftw(3) failed");
  1316. (*dents)[n].bsize = sb.st_blocks;
  1317. } else
  1318. (*dents)[n].bsize = blk_size;
  1319. } else
  1320. (*dents)[n].bsize = sb.st_blocks;
  1321. }
  1322. ++n;
  1323. }
  1324. if (bsizeorder) {
  1325. static struct statvfs svb;
  1326. if (statvfs(path, &svb) == -1)
  1327. fs_free = 0;
  1328. else
  1329. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1330. }
  1331. /* Should never be null */
  1332. if (closedir(dirp) == -1) {
  1333. if (*dents)
  1334. free(*dents);
  1335. printerr(1, "closedir");
  1336. }
  1337. return n;
  1338. }
  1339. static void
  1340. dentfree(struct entry *dents)
  1341. {
  1342. free(dents);
  1343. }
  1344. /* Return the position of the matching entry or 0 otherwise */
  1345. static int
  1346. dentfind(struct entry *dents, int n, char *path)
  1347. {
  1348. if (!path)
  1349. return 0;
  1350. static int i;
  1351. static char *p;
  1352. p = basename(path);
  1353. DPRINTF_S(p);
  1354. for (i = 0; i < n; ++i)
  1355. if (strcmp(p, dents[i].name) == 0)
  1356. return i;
  1357. return 0;
  1358. }
  1359. static int
  1360. populate(char *path, char *oldpath, char *fltr)
  1361. {
  1362. static regex_t re;
  1363. /* Can fail when permissions change while browsing */
  1364. if (canopendir(path) == 0)
  1365. return -1;
  1366. /* Search filter */
  1367. if (setfilter(&re, fltr) != 0)
  1368. return -1;
  1369. ndents = dentfill(path, &dents, visible, &re);
  1370. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1371. /* Find cur from history */
  1372. cur = dentfind(dents, ndents, oldpath);
  1373. return 0;
  1374. }
  1375. static void
  1376. redraw(char *path)
  1377. {
  1378. static char cwd[PATH_MAX];
  1379. static int nlines, i;
  1380. static size_t ncols;
  1381. nlines = MIN(LINES - 4, ndents);
  1382. /* Clean screen */
  1383. erase();
  1384. /* Strip trailing slashes */
  1385. for (i = strlen(path) - 1; i > 0; --i)
  1386. if (path[i] == '/')
  1387. path[i] = '\0';
  1388. else
  1389. break;
  1390. DPRINTF_D(cur);
  1391. DPRINTF_S(path);
  1392. /* No text wrapping in cwd line */
  1393. if (!realpath(path, cwd)) {
  1394. printmsg("Cannot resolve path");
  1395. return;
  1396. }
  1397. ncols = COLS;
  1398. if (ncols > PATH_MAX)
  1399. ncols = PATH_MAX;
  1400. cwd[ncols - strlen(CWD) - 1] = '\0';
  1401. printw(CWD "%s\n\n", cwd);
  1402. /* Print listing */
  1403. if (cur < (nlines >> 1)) {
  1404. for (i = 0; i < nlines; ++i)
  1405. printptr(&dents[i], i == cur);
  1406. } else if (cur >= ndents - (nlines >> 1)) {
  1407. for (i = ndents - nlines; i < ndents; ++i)
  1408. printptr(&dents[i], i == cur);
  1409. } else {
  1410. static int odd;
  1411. odd = ISODD(nlines);
  1412. nlines >>= 1;
  1413. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1414. printptr(&dents[i], i == cur);
  1415. }
  1416. if (showdetail) {
  1417. if (ndents) {
  1418. static char ind[2] = "\0\0";
  1419. static char sort[17];
  1420. if (mtimeorder)
  1421. sprintf(sort, "by time ");
  1422. else if (sizeorder)
  1423. sprintf(sort, "by size ");
  1424. else
  1425. sort[0] = '\0';
  1426. if (S_ISDIR(dents[cur].mode))
  1427. ind[0] = '/';
  1428. else if (S_ISLNK(dents[cur].mode))
  1429. ind[0] = '@';
  1430. else if (S_ISSOCK(dents[cur].mode))
  1431. ind[0] = '=';
  1432. else if (S_ISFIFO(dents[cur].mode))
  1433. ind[0] = '|';
  1434. else if (dents[cur].mode & 0100)
  1435. ind[0] = '*';
  1436. else
  1437. ind[0] = '\0';
  1438. if (!bsizeorder)
  1439. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  1440. replace_escape(dents[cur].name), ind);
  1441. else
  1442. sprintf(cwd,
  1443. "total %d by disk usage, %s free [%s%s]",
  1444. ndents, coolsize(fs_free),
  1445. replace_escape(dents[cur].name), ind);
  1446. printmsg(cwd);
  1447. } else
  1448. printmsg("0 items");
  1449. }
  1450. }
  1451. static void
  1452. browse(char *ipath, char *ifilter)
  1453. {
  1454. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  1455. static char lastdir[PATH_MAX];
  1456. static char fltr[LINE_MAX];
  1457. char *mime, *dir, *tmp, *run, *env;
  1458. struct stat sb;
  1459. int r, fd, presel;
  1460. enum action sel = SEL_RUNARG + 1;
  1461. xstrlcpy(path, ipath, PATH_MAX);
  1462. xstrlcpy(fltr, ifilter, LINE_MAX);
  1463. oldpath[0] = '\0';
  1464. newpath[0] = '\0';
  1465. lastdir[0] = '\0'; /* Can't move back from initial directory */
  1466. if (filtermode)
  1467. presel = FILTER;
  1468. else
  1469. presel = 0;
  1470. begin:
  1471. if (populate(path, oldpath, fltr) == -1) {
  1472. printwarn();
  1473. goto nochange;
  1474. }
  1475. for (;;) {
  1476. redraw(path);
  1477. nochange:
  1478. /* Exit if parent has exited */
  1479. if (getppid() == 1)
  1480. _exit(0);
  1481. sel = nextsel(&run, &env, &presel);
  1482. switch (sel) {
  1483. case SEL_CDQUIT:
  1484. {
  1485. char *tmpfile = "/tmp/nnn";
  1486. tmp = getenv("NNN_TMPFILE");
  1487. if (tmp)
  1488. tmpfile = tmp;
  1489. FILE *fp = fopen(tmpfile, "w");
  1490. if (fp) {
  1491. fprintf(fp, "cd \"%s\"", path);
  1492. fclose(fp);
  1493. }
  1494. /* Fall through to exit */
  1495. } // fallthrough
  1496. case SEL_QUIT:
  1497. dentfree(dents);
  1498. return;
  1499. case SEL_BACK:
  1500. /* There is no going back */
  1501. if (path[0] == '/' && path[1] == '\0') {
  1502. printmsg("You are at /");
  1503. goto nochange;
  1504. }
  1505. dir = xdirname(path);
  1506. if (canopendir(dir) == 0) {
  1507. printwarn();
  1508. goto nochange;
  1509. }
  1510. /* Save history */
  1511. xstrlcpy(oldpath, path, PATH_MAX);
  1512. /* Save last working directory */
  1513. xstrlcpy(lastdir, path, PATH_MAX);
  1514. xstrlcpy(path, dir, PATH_MAX);
  1515. /* Reset filter */
  1516. xstrlcpy(fltr, ifilter, LINE_MAX);
  1517. if (filtermode)
  1518. presel = FILTER;
  1519. goto begin;
  1520. case SEL_GOIN:
  1521. /* Cannot descend in empty directories */
  1522. if (ndents == 0)
  1523. goto begin;
  1524. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1525. DPRINTF_S(newpath);
  1526. /* Get path info */
  1527. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1528. if (fd == -1) {
  1529. printwarn();
  1530. goto nochange;
  1531. }
  1532. r = fstat(fd, &sb);
  1533. if (r == -1) {
  1534. printwarn();
  1535. close(fd);
  1536. goto nochange;
  1537. }
  1538. close(fd);
  1539. DPRINTF_U(sb.st_mode);
  1540. switch (sb.st_mode & S_IFMT) {
  1541. case S_IFDIR:
  1542. if (canopendir(newpath) == 0) {
  1543. printwarn();
  1544. goto nochange;
  1545. }
  1546. /* Save last working directory */
  1547. xstrlcpy(lastdir, path, PATH_MAX);
  1548. xstrlcpy(path, newpath, PATH_MAX);
  1549. oldpath[0] = '\0';
  1550. /* Reset filter */
  1551. xstrlcpy(fltr, ifilter, LINE_MAX);
  1552. if (filtermode)
  1553. presel = FILTER;
  1554. goto begin;
  1555. case S_IFREG:
  1556. {
  1557. /* If NNN_USE_EDITOR is set,
  1558. * open text in EDITOR
  1559. */
  1560. if (editor) {
  1561. mime = getmime(dents[cur].name);
  1562. if (mime) {
  1563. spawn(editor, newpath, NULL,
  1564. NULL, 0b10000000);
  1565. continue;
  1566. }
  1567. /* Recognize and open plain
  1568. * text files with vi
  1569. */
  1570. if (get_output(g_buf, MAX_CMD_LEN,
  1571. "file", "-bi",
  1572. newpath, 0) == NULL)
  1573. continue;
  1574. if (strstr(g_buf, "text/") == g_buf) {
  1575. spawn(editor, newpath, NULL,
  1576. NULL, 0b10000000);
  1577. continue;
  1578. }
  1579. }
  1580. /* Invoke desktop opener as last resort */
  1581. spawn(utils[0], newpath, NULL, NULL, 0b100);
  1582. continue;
  1583. }
  1584. default:
  1585. printmsg("Unsupported file");
  1586. goto nochange;
  1587. }
  1588. case SEL_FLTR:
  1589. presel = readln(path);
  1590. xstrlcpy(fltr, ifilter, LINE_MAX);
  1591. DPRINTF_S(fltr);
  1592. /* Save current */
  1593. if (ndents > 0)
  1594. mkpath(path, dents[cur].name, oldpath,
  1595. PATH_MAX);
  1596. goto nochange;
  1597. case SEL_MFLTR:
  1598. filtermode = !filtermode;
  1599. if (filtermode)
  1600. presel = FILTER;
  1601. else
  1602. printmsg("navigate-as-you-type off");
  1603. goto nochange;
  1604. case SEL_SEARCH:
  1605. spawn(player, path, "search", NULL, 0b10000000);
  1606. break;
  1607. case SEL_NEXT:
  1608. if (cur < ndents - 1)
  1609. ++cur;
  1610. else if (ndents)
  1611. /* Roll over, set cursor to first entry */
  1612. cur = 0;
  1613. break;
  1614. case SEL_PREV:
  1615. if (cur > 0)
  1616. --cur;
  1617. else if (ndents)
  1618. /* Roll over, set cursor to last entry */
  1619. cur = ndents - 1;
  1620. break;
  1621. case SEL_PGDN:
  1622. if (cur < ndents - 1)
  1623. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1624. break;
  1625. case SEL_PGUP:
  1626. if (cur > 0)
  1627. cur -= MIN((LINES - 4) / 2, cur);
  1628. break;
  1629. case SEL_HOME:
  1630. cur = 0;
  1631. break;
  1632. case SEL_END:
  1633. cur = ndents - 1;
  1634. break;
  1635. case SEL_CD:
  1636. {
  1637. static char *input;
  1638. static int truecd;
  1639. /* Save the program start dir */
  1640. tmp = getcwd(newpath, PATH_MAX);
  1641. if (tmp == NULL) {
  1642. printwarn();
  1643. goto nochange;
  1644. }
  1645. /* Switch to current path for readline(3) */
  1646. if (chdir(path) == -1) {
  1647. printwarn();
  1648. goto nochange;
  1649. }
  1650. exitcurses();
  1651. tmp = readline("chdir: ");
  1652. initcurses();
  1653. /* Change back to program start dir */
  1654. if (chdir(newpath) == -1)
  1655. printwarn();
  1656. if (tmp[0] == '\0')
  1657. break;
  1658. /* Add to readline(3) history */
  1659. add_history(tmp);
  1660. input = tmp;
  1661. tmp = strstrip(tmp);
  1662. if (tmp[0] == '\0') {
  1663. free(input);
  1664. break;
  1665. }
  1666. truecd = 0;
  1667. if (tmp[0] == '~') {
  1668. /* Expand ~ to HOME absolute path */
  1669. char *home = getenv("HOME");
  1670. if (home)
  1671. snprintf(newpath, PATH_MAX, "%s%s",
  1672. home, tmp + 1);
  1673. else {
  1674. free(input);
  1675. printmsg("HOME not set");
  1676. goto nochange;
  1677. }
  1678. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1679. if (lastdir[0] == '\0') {
  1680. free(input);
  1681. break;
  1682. }
  1683. /* Switch to last visited dir */
  1684. xstrlcpy(newpath, lastdir, PATH_MAX);
  1685. truecd = 1;
  1686. } else if ((r = all_dots(tmp))) {
  1687. if (r == 1) {
  1688. /* Always in the current dir */
  1689. free(input);
  1690. break;
  1691. }
  1692. --r;
  1693. dir = path;
  1694. for (fd = 0; fd < r; ++fd) {
  1695. /* Reached / ? */
  1696. if (path[0] == '/' && path[1] == '\0') {
  1697. /* If it's a cd .. at / */
  1698. if (fd == 0) {
  1699. printmsg("You are at /");
  1700. free(input);
  1701. goto nochange;
  1702. }
  1703. /* Can't cd beyond / anyway */
  1704. break;
  1705. }
  1706. dir = xdirname(dir);
  1707. if (canopendir(dir) == 0) {
  1708. printwarn();
  1709. free(input);
  1710. goto nochange;
  1711. }
  1712. }
  1713. truecd = 1;
  1714. /* Save the path in case of cd ..
  1715. * We mark the current dir in parent dir
  1716. */
  1717. if (r == 1) {
  1718. xstrlcpy(oldpath, path, PATH_MAX);
  1719. truecd = 2;
  1720. }
  1721. xstrlcpy(newpath, dir, PATH_MAX);
  1722. } else
  1723. mkpath(path, tmp, newpath, PATH_MAX);
  1724. free(input);
  1725. if (canopendir(newpath) == 0) {
  1726. printwarn();
  1727. break;
  1728. }
  1729. if (truecd == 0) {
  1730. /* Probable change in dir */
  1731. /* No-op if it's the same directory */
  1732. if (strcmp(path, newpath) == 0)
  1733. break;
  1734. oldpath[0] = '\0';
  1735. } else if (truecd == 1)
  1736. /* Sure change in dir */
  1737. oldpath[0] = '\0';
  1738. /* Save last working directory */
  1739. xstrlcpy(lastdir, path, PATH_MAX);
  1740. /* Save the newly opted dir in path */
  1741. xstrlcpy(path, newpath, PATH_MAX);
  1742. /* Reset filter */
  1743. xstrlcpy(fltr, ifilter, LINE_MAX);
  1744. DPRINTF_S(path);
  1745. if (filtermode)
  1746. presel = FILTER;
  1747. goto begin;
  1748. }
  1749. case SEL_CDHOME:
  1750. tmp = getenv("HOME");
  1751. if (tmp == NULL) {
  1752. clearprompt();
  1753. goto nochange;
  1754. }
  1755. if (canopendir(tmp) == 0) {
  1756. printwarn();
  1757. goto nochange;
  1758. }
  1759. if (strcmp(path, tmp) == 0)
  1760. break;
  1761. /* Save last working directory */
  1762. xstrlcpy(lastdir, path, PATH_MAX);
  1763. xstrlcpy(path, tmp, PATH_MAX);
  1764. oldpath[0] = '\0';
  1765. /* Reset filter */
  1766. xstrlcpy(fltr, ifilter, LINE_MAX);
  1767. DPRINTF_S(path);
  1768. if (filtermode)
  1769. presel = FILTER;
  1770. goto begin;
  1771. case SEL_CDBEGIN:
  1772. if (canopendir(ipath) == 0) {
  1773. printwarn();
  1774. goto nochange;
  1775. }
  1776. if (strcmp(path, ipath) == 0)
  1777. break;
  1778. /* Save last working directory */
  1779. xstrlcpy(lastdir, path, PATH_MAX);
  1780. xstrlcpy(path, ipath, PATH_MAX);
  1781. oldpath[0] = '\0';
  1782. /* Reset filter */
  1783. xstrlcpy(fltr, ifilter, LINE_MAX);
  1784. DPRINTF_S(path);
  1785. if (filtermode)
  1786. presel = FILTER;
  1787. goto begin;
  1788. case SEL_CDLAST:
  1789. if (lastdir[0] == '\0')
  1790. break;
  1791. if (canopendir(lastdir) == 0) {
  1792. printwarn();
  1793. goto nochange;
  1794. }
  1795. xstrlcpy(newpath, lastdir, PATH_MAX);
  1796. xstrlcpy(lastdir, path, PATH_MAX);
  1797. xstrlcpy(path, newpath, PATH_MAX);
  1798. oldpath[0] = '\0';
  1799. /* Reset filter */
  1800. xstrlcpy(fltr, ifilter, LINE_MAX);
  1801. DPRINTF_S(path);
  1802. if (filtermode)
  1803. presel = FILTER;
  1804. goto begin;
  1805. case SEL_CDBM:
  1806. printprompt("key: ");
  1807. tmp = readinput();
  1808. if (tmp == NULL) {
  1809. clearprompt();
  1810. goto nochange;
  1811. }
  1812. clearprompt();
  1813. for (r = 0; bookmark[r].key && r < MAX_BM; ++r) {
  1814. if (strcmp(bookmark[r].key, tmp) == 0) {
  1815. if (bookmark[r].loc[0] == '~') {
  1816. /* Expand ~ to HOME */
  1817. char *home = getenv("HOME");
  1818. if (home)
  1819. snprintf(newpath,
  1820. PATH_MAX,
  1821. "%s%s",
  1822. home,
  1823. bookmark[r].loc
  1824. + 1);
  1825. else {
  1826. printmsg("HOME not set");
  1827. goto nochange;
  1828. }
  1829. } else
  1830. mkpath(path, bookmark[r].loc,
  1831. newpath, PATH_MAX);
  1832. if (canopendir(newpath) == 0) {
  1833. printwarn();
  1834. goto nochange;
  1835. }
  1836. if (strcmp(path, newpath) == 0)
  1837. break;
  1838. oldpath[0] = '\0';
  1839. break;
  1840. }
  1841. }
  1842. if (!bookmark[r].key) {
  1843. printmsg("No matching bookmark");
  1844. goto nochange;
  1845. }
  1846. /* Save last working directory */
  1847. xstrlcpy(lastdir, path, PATH_MAX);
  1848. /* Save the newly opted dir in path */
  1849. xstrlcpy(path, newpath, PATH_MAX);
  1850. /* Reset filter */
  1851. xstrlcpy(fltr, ifilter, LINE_MAX);
  1852. DPRINTF_S(path);
  1853. if (filtermode)
  1854. presel = FILTER;
  1855. goto begin;
  1856. case SEL_TOGGLEDOT:
  1857. showhidden ^= 1;
  1858. initfilter(showhidden, &ifilter);
  1859. xstrlcpy(fltr, ifilter, LINE_MAX);
  1860. goto begin;
  1861. case SEL_DETAIL:
  1862. showdetail = !showdetail;
  1863. showdetail ? (printptr = &printent_long)
  1864. : (printptr = &printent);
  1865. /* Save current */
  1866. if (ndents > 0)
  1867. mkpath(path, dents[cur].name, oldpath,
  1868. PATH_MAX);
  1869. goto begin;
  1870. case SEL_STATS:
  1871. {
  1872. struct stat sb;
  1873. if (ndents > 0) {
  1874. mkpath(path, dents[cur].name, oldpath,
  1875. PATH_MAX);
  1876. r = lstat(oldpath, &sb);
  1877. if (r == -1) {
  1878. if (dents)
  1879. dentfree(dents);
  1880. printerr(1, "lstat");
  1881. } else {
  1882. r = show_stats(oldpath, dents[cur].name,
  1883. &sb);
  1884. if (r < 0) {
  1885. printmsg(strerror(errno));
  1886. goto nochange;
  1887. }
  1888. }
  1889. }
  1890. break;
  1891. }
  1892. case SEL_MEDIA:
  1893. if (ndents > 0) {
  1894. mkpath(path, dents[cur].name, oldpath,
  1895. PATH_MAX);
  1896. if (show_mediainfo(oldpath, NULL) == -1) {
  1897. printmsg("mediainfo missing");
  1898. goto nochange;
  1899. }
  1900. }
  1901. break;
  1902. case SEL_FMEDIA:
  1903. if (ndents > 0) {
  1904. mkpath(path, dents[cur].name, oldpath,
  1905. PATH_MAX);
  1906. if (show_mediainfo(oldpath, "-f") == -1) {
  1907. printmsg("mediainfo missing");
  1908. goto nochange;
  1909. }
  1910. }
  1911. break;
  1912. case SEL_DFB:
  1913. if (!desktop_manager) {
  1914. printmsg("NNN_DE_FILE_MANAGER not set");
  1915. goto nochange;
  1916. }
  1917. spawn(desktop_manager, path, NULL, path, 0b110);
  1918. break;
  1919. case SEL_FSIZE:
  1920. sizeorder = !sizeorder;
  1921. mtimeorder = 0;
  1922. bsizeorder = 0;
  1923. /* Save current */
  1924. if (ndents > 0)
  1925. mkpath(path, dents[cur].name, oldpath,
  1926. PATH_MAX);
  1927. goto begin;
  1928. case SEL_BSIZE:
  1929. bsizeorder = !bsizeorder;
  1930. if (bsizeorder) {
  1931. showdetail = 1;
  1932. printptr = &printent_long;
  1933. }
  1934. mtimeorder = 0;
  1935. sizeorder = 0;
  1936. /* Save current */
  1937. if (ndents > 0)
  1938. mkpath(path, dents[cur].name, oldpath,
  1939. PATH_MAX);
  1940. goto begin;
  1941. case SEL_MTIME:
  1942. mtimeorder = !mtimeorder;
  1943. sizeorder = 0;
  1944. bsizeorder = 0;
  1945. /* Save current */
  1946. if (ndents > 0)
  1947. mkpath(path, dents[cur].name, oldpath,
  1948. PATH_MAX);
  1949. goto begin;
  1950. case SEL_REDRAW:
  1951. /* Save current */
  1952. if (ndents > 0)
  1953. mkpath(path, dents[cur].name, oldpath,
  1954. PATH_MAX);
  1955. goto begin;
  1956. case SEL_COPY:
  1957. if (copier && ndents) {
  1958. if (strcmp(path, "/") == 0)
  1959. snprintf(newpath, PATH_MAX, "/%s",
  1960. dents[cur].name);
  1961. else
  1962. snprintf(newpath, PATH_MAX, "%s/%s",
  1963. path, dents[cur].name);
  1964. spawn(copier, newpath, NULL, NULL, 0b0);
  1965. printmsg(newpath);
  1966. } else if (!copier)
  1967. printmsg("NNN_COPIER is not set");
  1968. goto nochange;
  1969. case SEL_HELP:
  1970. show_help();
  1971. break;
  1972. case SEL_RUN:
  1973. run = xgetenv(env, run);
  1974. spawn(run, NULL, NULL, path, 0b10000001);
  1975. /* Repopulate as directory content may have changed */
  1976. goto begin;
  1977. case SEL_RUNARG:
  1978. run = xgetenv(env, run);
  1979. spawn(run, dents[cur].name, NULL, path, 0b10000000);
  1980. break;
  1981. }
  1982. /* Screensaver */
  1983. if (idletimeout != 0 && idle == idletimeout) {
  1984. idle = 0;
  1985. spawn(player, "", "screensaver", NULL, 0b10001000);
  1986. }
  1987. }
  1988. }
  1989. static void
  1990. usage(void)
  1991. {
  1992. printf("usage: nnn [-l] [-i] [-p custom_nlay] [-S] [-v] [-h] [PATH]\n\n\
  1993. The missing terminal file browser for X.\n\n\
  1994. positional arguments:\n\
  1995. PATH directory to open [default: current dir]\n\n\
  1996. optional arguments:\n\
  1997. -l start in light mode (fewer details)\n\
  1998. -i start in navigate-as-you-type mode\n\
  1999. -p path to custom nlay\n\
  2000. -S start in disk usage analyzer mode\n\
  2001. -v show program version and exit\n\
  2002. -h show this help and exit\n\n\
  2003. Version: %s\n\
  2004. License: BSD 2-Clause\n\
  2005. Webpage: https://github.com/jarun/nnn\n", VERSION);
  2006. exit(0);
  2007. }
  2008. int
  2009. main(int argc, char *argv[])
  2010. {
  2011. char cwd[PATH_MAX], *ipath;
  2012. char *ifilter, *bmstr;
  2013. int opt = 0;
  2014. /* Confirm we are in a terminal */
  2015. if (!isatty(0) || !isatty(1)) {
  2016. fprintf(stderr, "stdin or stdout is not a tty\n");
  2017. exit(1);
  2018. }
  2019. while ((opt = getopt(argc, argv, "dlSip:vh")) != -1) {
  2020. switch (opt) {
  2021. case 'S':
  2022. bsizeorder = 1;
  2023. break;
  2024. case 'l':
  2025. showdetail = 0;
  2026. printptr = &printent;
  2027. break;
  2028. case 'i':
  2029. filtermode = 1;
  2030. break;
  2031. case 'p':
  2032. player = optarg;
  2033. break;
  2034. case 'v':
  2035. printf("%s\n", VERSION);
  2036. return 0;
  2037. case 'd':
  2038. fprintf(stderr, "Option -d is deprecated and will be removed, detail view mode is default now.\n");
  2039. break;
  2040. case 'h': // fallthrough
  2041. default:
  2042. usage();
  2043. }
  2044. }
  2045. if (argc == optind) {
  2046. /* Start in the current directory */
  2047. ipath = getcwd(cwd, PATH_MAX);
  2048. if (ipath == NULL)
  2049. ipath = "/";
  2050. } else {
  2051. ipath = realpath(argv[optind], cwd);
  2052. if (!ipath) {
  2053. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2054. exit(1);
  2055. }
  2056. }
  2057. open_max = max_openfds();
  2058. if (getuid() == 0)
  2059. showhidden = 1;
  2060. initfilter(showhidden, &ifilter);
  2061. /* Parse bookmarks string, if available */
  2062. bmstr = getenv("NNN_BMS");
  2063. if (bmstr)
  2064. parsebmstr(bmstr);
  2065. /* Edit text in EDITOR, if opted */
  2066. if (getenv("NNN_USE_EDITOR"))
  2067. editor = xgetenv("EDITOR", "vi");
  2068. /* Set player if not set already */
  2069. if (!player)
  2070. player = utils[1];
  2071. /* Get the desktop file browser, if set */
  2072. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2073. /* Get screensaver wait time, if set; copier used as tmp var */
  2074. copier = getenv("NNN_IDLE_TIMEOUT");
  2075. if (copier)
  2076. idletimeout = abs(atoi(copier));
  2077. /* Get the default copier, if set */
  2078. copier = getenv("NNN_COPIER");
  2079. signal(SIGINT, SIG_IGN);
  2080. /* Test initial path */
  2081. if (canopendir(ipath) == 0) {
  2082. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2083. exit(1);
  2084. }
  2085. #ifdef DEBUGMODE
  2086. enabledbg();
  2087. #endif
  2088. /* Set locale */
  2089. setlocale(LC_ALL, "");
  2090. initcurses();
  2091. browse(ipath, ifilter);
  2092. exitcurses();
  2093. #ifdef DEBUGMODE
  2094. disabledbg();
  2095. #endif
  2096. exit(0);
  2097. }