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.
 
 
 
 
 
 

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