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.
 
 
 
 
 
 

1913 lines
40 KiB

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