My build of nnn with minor changes
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

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