My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

1828 lignes
38 KiB

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