My build of nnn with minor changes
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

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