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.

nnn.c 23 KiB

il y a 9 ans
il y a 10 ans
il y a 9 ans
il y a 9 ans
il y a 10 ans
il y a 10 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 10 ans
il y a 8 ans
il y a 10 ans
il y a 10 ans
il y a 10 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 10 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 9 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 10 ans
il y a 10 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 9 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 8 ans
il y a 10 ans
il y a 8 ans
il y a 9 ans
il y a 9 ans
il y a 9 ans
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  1. /* See LICENSE file for copyright and license details. */
  2. #include <sys/stat.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. #include <curses.h>
  6. #include <dirent.h>
  7. #include <errno.h>
  8. #include <fcntl.h>
  9. #include <limits.h>
  10. #include <locale.h>
  11. #include <regex.h>
  12. #include <signal.h>
  13. #include <stdarg.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <unistd.h>
  18. #include <time.h>
  19. #ifdef DEBUG
  20. #define DEBUG_FD 8
  21. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  22. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  23. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  24. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=0x%p\n", x)
  25. #else
  26. #define DPRINTF_D(x)
  27. #define DPRINTF_U(x)
  28. #define DPRINTF_S(x)
  29. #define DPRINTF_P(x)
  30. #endif /* DEBUG */
  31. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  32. #undef MIN
  33. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  34. #define ISODD(x) ((x) & 1)
  35. #define CONTROL(c) ((c) ^ 0x40)
  36. #define TOUPPER(ch) \
  37. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  38. #define MAX_CMD_LEN (PATH_MAX << 1)
  39. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  40. struct assoc {
  41. char *regex; /* Regex to match on filename */
  42. char *bin; /* Program */
  43. };
  44. /* Supported actions */
  45. enum action {
  46. SEL_QUIT = 1,
  47. SEL_BACK,
  48. SEL_GOIN,
  49. SEL_FLTR,
  50. SEL_NEXT,
  51. SEL_PREV,
  52. SEL_PGDN,
  53. SEL_PGUP,
  54. SEL_HOME,
  55. SEL_END,
  56. SEL_CD,
  57. SEL_CDHOME,
  58. SEL_TOGGLEDOT,
  59. SEL_DETAIL,
  60. SEL_FSIZE,
  61. SEL_MTIME,
  62. SEL_REDRAW,
  63. SEL_COPY,
  64. SEL_RUN,
  65. SEL_RUNARG,
  66. };
  67. struct key {
  68. int sym; /* Key pressed */
  69. enum action act; /* Action */
  70. char *run; /* Program to run */
  71. char *env; /* Environment variable to run */
  72. };
  73. #include "config.h"
  74. typedef struct entry {
  75. char name[PATH_MAX];
  76. mode_t mode;
  77. time_t t;
  78. off_t size;
  79. } *pEntry;
  80. /* Global context */
  81. static struct entry *dents;
  82. static int ndents, cur;
  83. static int idle;
  84. static char *opener;
  85. static char *fallback_opener;
  86. static char *copier;
  87. static const char* size_units[] = {"B", "K", "M", "G", "T", "P", "E", "Z", "Y"};
  88. /*
  89. * Layout:
  90. * .---------
  91. * | cwd: /mnt/path
  92. * |
  93. * | file0
  94. * | file1
  95. * | > file2
  96. * | file3
  97. * | file4
  98. * ...
  99. * | filen
  100. * |
  101. * | Permission denied
  102. * '------
  103. */
  104. static void printmsg(char *);
  105. static void printwarn(void);
  106. static void printerr(int, char *);
  107. static int
  108. xprintf(int fd, const char *fmt, ...)
  109. {
  110. char buf[BUFSIZ];
  111. int r;
  112. va_list ap;
  113. va_start(ap, fmt);
  114. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  115. if (r > 0)
  116. r = write(fd, buf, r);
  117. va_end(ap);
  118. return r;
  119. }
  120. static void *
  121. xrealloc(void *p, size_t size)
  122. {
  123. p = realloc(p, size);
  124. if (p == NULL)
  125. printerr(1, "realloc");
  126. return p;
  127. }
  128. static size_t
  129. xstrlcpy(char *dest, const char *src, size_t n)
  130. {
  131. size_t i;
  132. for (i = 0; i < n && *src; i++)
  133. *dest++ = *src++;
  134. if (n) {
  135. *dest = '\0';
  136. #ifdef CHECK_XSTRLCPY_RET
  137. /* Compiling this out as we are not checking
  138. the return value anywhere (controlled case).
  139. Just returning the number of bytes copied. */
  140. while(*src++)
  141. i++;
  142. #endif
  143. }
  144. return i;
  145. }
  146. /*
  147. * The poor man's implementation of memrchr().
  148. * We are only looking for '/' in this program.
  149. */
  150. static void *
  151. xmemrchr(const void *s, int c, size_t n)
  152. {
  153. unsigned char *p;
  154. unsigned char ch = (unsigned char)c;
  155. if (!s || !n)
  156. return NULL;
  157. p = (unsigned char *)s + n - 1;
  158. while(n--)
  159. if ((*p--) == ch)
  160. return ++p;
  161. return NULL;
  162. }
  163. #if 0
  164. /* Some implementations of dirname(3) may modify `path' and some
  165. * return a pointer inside `path'. */
  166. static char *
  167. xdirname(const char *path)
  168. {
  169. static char out[PATH_MAX];
  170. char tmp[PATH_MAX], *p;
  171. xstrlcpy(tmp, path, sizeof(tmp));
  172. p = dirname(tmp);
  173. if (p == NULL)
  174. printerr(1, "dirname");
  175. xstrlcpy(out, p, sizeof(out));
  176. return out;
  177. }
  178. #endif
  179. /*
  180. * The following dirname() implementation does not
  181. * change the input. We use a copy of the original.
  182. *
  183. * Modified from the glibc (GNU LGPL) version.
  184. */
  185. static char *
  186. xdirname(const char *path)
  187. {
  188. static char name[PATH_MAX];
  189. char *last_slash;
  190. xstrlcpy(name, path, PATH_MAX);
  191. /* Find last '/'. */
  192. last_slash = strrchr(name, '/');
  193. if (last_slash != NULL && last_slash != name && last_slash[1] == '\0') {
  194. /* Determine whether all remaining characters are slashes. */
  195. char *runp;
  196. for (runp = last_slash; runp != name; --runp)
  197. if (runp[-1] != '/')
  198. break;
  199. /* The '/' is the last character, we have to look further. */
  200. if (runp != name)
  201. last_slash = xmemrchr(name, '/', runp - name);
  202. }
  203. if (last_slash != NULL) {
  204. /* Determine whether all remaining characters are slashes. */
  205. char *runp;
  206. for (runp = last_slash; runp != name; --runp)
  207. if (runp[-1] != '/')
  208. break;
  209. /* Terminate the name. */
  210. if (runp == name) {
  211. /* The last slash is the first character in the string.
  212. We have to return "/". As a special case we have to
  213. return "//" if there are exactly two slashes at the
  214. beginning of the string. See XBD 4.10 Path Name
  215. Resolution for more information. */
  216. if (last_slash == name + 1)
  217. ++last_slash;
  218. else
  219. last_slash = name + 1;
  220. } else
  221. last_slash = runp;
  222. last_slash[0] = '\0';
  223. } else {
  224. /* This assignment is ill-designed but the XPG specs require to
  225. return a string containing "." in any case no directory part
  226. is found and so a static and constant string is required. */
  227. name[0] = '.';
  228. name[1] = '\0';
  229. }
  230. return name;
  231. }
  232. static void
  233. spawn(char *file, char *arg, char *dir)
  234. {
  235. pid_t pid;
  236. int status;
  237. pid = fork();
  238. if (pid == 0) {
  239. if (dir != NULL)
  240. status = chdir(dir);
  241. execlp(file, file, arg, NULL);
  242. _exit(1);
  243. } else {
  244. /* Ignore interruptions */
  245. while (waitpid(pid, &status, 0) == -1)
  246. DPRINTF_D(status);
  247. DPRINTF_D(pid);
  248. }
  249. }
  250. static char *
  251. xgetenv(char *name, char *fallback)
  252. {
  253. char *value;
  254. if (name == NULL)
  255. return fallback;
  256. value = getenv(name);
  257. return value && value[0] ? value : fallback;
  258. }
  259. int xisdigit(const char c) {
  260. if (c >= '0' && c <= '9') \
  261. return 1; \
  262. return 0;
  263. }
  264. /*
  265. * We assume none of the strings are NULL.
  266. *
  267. * Let's have the logic to sort numeric names in numeric order.
  268. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  269. *
  270. * If the absolute numeric values are same, we fallback to alphasort.
  271. */
  272. static int
  273. xstricmp(const char *s1, const char *s2)
  274. {
  275. static char *c1, *c2;
  276. static long long num1, num2;
  277. num1 = strtoll(s1, &c1, 10);
  278. num2 = strtoll(s2, &c2, 10);
  279. if (*c1 == '\0' && *c2 == '\0') {
  280. if (num1 != num2) {
  281. if (num1 > num2)
  282. return 1;
  283. else
  284. return -1;
  285. }
  286. } else if (*c1 == '\0' && *c2 != '\0')
  287. return -1;
  288. else if (*c1 != '\0' && *c2 == '\0')
  289. return 1;
  290. while (*s2 && *s1 && TOUPPER(*s1) == TOUPPER(*s2))
  291. s1++, s2++;
  292. /* In case of alphabetically same names, make sure
  293. lower case one comes before upper case one */
  294. if (!*s1 && !*s2)
  295. return 1;
  296. return (int) (TOUPPER(*s1) - TOUPPER(*s2));
  297. }
  298. static char *
  299. openwith(char *file)
  300. {
  301. regex_t regex;
  302. char *bin = NULL;
  303. unsigned int i;
  304. for (i = 0; i < LEN(assocs); i++) {
  305. if (regcomp(&regex, assocs[i].regex,
  306. REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  307. continue;
  308. if (regexec(&regex, file, 0, NULL, 0) == 0) {
  309. bin = assocs[i].bin;
  310. break;
  311. }
  312. }
  313. DPRINTF_S(bin);
  314. return bin;
  315. }
  316. static int
  317. setfilter(regex_t *regex, char *filter)
  318. {
  319. char errbuf[LINE_MAX];
  320. size_t len;
  321. int r;
  322. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  323. if (r != 0) {
  324. len = COLS;
  325. if (len > sizeof(errbuf))
  326. len = sizeof(errbuf);
  327. regerror(r, regex, errbuf, len);
  328. printmsg(errbuf);
  329. }
  330. return r;
  331. }
  332. static void
  333. initfilter(int dot, char **ifilter)
  334. {
  335. *ifilter = dot ? "." : "^[^.]";
  336. }
  337. static int
  338. visible(regex_t *regex, char *file)
  339. {
  340. return regexec(regex, file, 0, NULL, 0) == 0;
  341. }
  342. static int
  343. entrycmp(const void *va, const void *vb)
  344. {
  345. static pEntry pa, pb;
  346. pa = (pEntry)va;
  347. pb = (pEntry)vb;
  348. /* Sort directories first */
  349. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  350. return 1;
  351. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  352. return -1;
  353. /* Do the actual sorting */
  354. if (mtimeorder)
  355. return pb->t - pa->t;
  356. if (sizeorder)
  357. if (pb->size != pa->size)
  358. return pb->size - pa->size;
  359. return xstricmp(pa->name, pb->name);
  360. }
  361. static void
  362. initcurses(void)
  363. {
  364. if (initscr() == NULL) {
  365. char *term = getenv("TERM");
  366. if (term != NULL)
  367. fprintf(stderr, "error opening terminal: %s\n", term);
  368. else
  369. fprintf(stderr, "failed to initialize curses\n");
  370. exit(1);
  371. }
  372. cbreak();
  373. noecho();
  374. nonl();
  375. intrflush(stdscr, FALSE);
  376. keypad(stdscr, TRUE);
  377. curs_set(FALSE); /* Hide cursor */
  378. timeout(1000); /* One second */
  379. }
  380. static void
  381. exitcurses(void)
  382. {
  383. endwin(); /* Restore terminal */
  384. }
  385. /* Messages show up at the bottom */
  386. static void
  387. printmsg(char *msg)
  388. {
  389. move(LINES - 1, 0);
  390. printw("%s\n", msg);
  391. }
  392. /* Display warning as a message */
  393. static void
  394. printwarn(void)
  395. {
  396. printmsg(strerror(errno));
  397. }
  398. /* Kill curses and display error before exiting */
  399. static void
  400. printerr(int ret, char *prefix)
  401. {
  402. exitcurses();
  403. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  404. exit(ret);
  405. }
  406. /* Clear the last line */
  407. static void
  408. clearprompt(void)
  409. {
  410. printmsg("");
  411. }
  412. /* Print prompt on the last line */
  413. static void
  414. printprompt(char *str)
  415. {
  416. clearprompt();
  417. printw(str);
  418. }
  419. /* Returns SEL_* if key is bound and 0 otherwise.
  420. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}) */
  421. static int
  422. nextsel(char **run, char **env)
  423. {
  424. int c;
  425. unsigned int i;
  426. c = getch();
  427. if (c == -1)
  428. idle++;
  429. else
  430. idle = 0;
  431. for (i = 0; i < LEN(bindings); i++)
  432. if (c == bindings[i].sym) {
  433. *run = bindings[i].run;
  434. *env = bindings[i].env;
  435. return bindings[i].act;
  436. }
  437. return 0;
  438. }
  439. static char *
  440. readln(void)
  441. {
  442. static char ln[LINE_MAX];
  443. timeout(-1);
  444. echo();
  445. curs_set(TRUE);
  446. memset(ln, 0, sizeof(ln));
  447. wgetnstr(stdscr, ln, sizeof(ln) - 1);
  448. noecho();
  449. curs_set(FALSE);
  450. timeout(1000);
  451. return ln[0] ? ln : NULL;
  452. }
  453. static int
  454. canopendir(char *path)
  455. {
  456. DIR *dirp;
  457. dirp = opendir(path);
  458. if (dirp == NULL)
  459. return 0;
  460. closedir(dirp);
  461. return 1;
  462. }
  463. /*
  464. * Returns "dir/name or "/name"
  465. */
  466. static char *
  467. mkpath(char *dir, char *name, char *out, size_t n)
  468. {
  469. /* Handle absolute path */
  470. if (name[0] == '/')
  471. xstrlcpy(out, name, n);
  472. else {
  473. /* Handle root case */
  474. if (strcmp(dir, "/") == 0)
  475. snprintf(out, n, "/%s", name);
  476. else
  477. snprintf(out, n, "%s/%s", dir, name);
  478. }
  479. return out;
  480. }
  481. static void
  482. printent(struct entry *ent, int active)
  483. {
  484. if (S_ISDIR(ent->mode))
  485. printw("%s%s/\n", CURSYM(active), ent->name);
  486. else if (S_ISLNK(ent->mode))
  487. printw("%s%s@\n", CURSYM(active), ent->name);
  488. else if (S_ISSOCK(ent->mode))
  489. printw("%s%s=\n", CURSYM(active), ent->name);
  490. else if (S_ISFIFO(ent->mode))
  491. printw("%s%s|\n", CURSYM(active), ent->name);
  492. else if (ent->mode & S_IXUSR)
  493. printw("%s%s*\n", CURSYM(active), ent->name);
  494. else
  495. printw("%s%s\n", CURSYM(active), ent->name);
  496. }
  497. static void (*printptr)(struct entry *ent, int active) = &printent;
  498. static char*
  499. coolsize(off_t size)
  500. {
  501. static char size_buf[12]; /* Buffer to hold human readable size */
  502. int i = 0;
  503. long double fsize = (double)size;
  504. while (fsize > 1024) {
  505. fsize /= 1024;
  506. i++;
  507. }
  508. snprintf(size_buf, 12, "%.*Lf%s", i, fsize, size_units[i]);
  509. return size_buf;
  510. }
  511. static void
  512. printent_long(struct entry *ent, int active)
  513. {
  514. static char buf[18];
  515. static const struct tm *p;
  516. p = localtime(&ent->t);
  517. strftime(buf, 18, "%b %d %H:%M %Y", p);
  518. if (active)
  519. attron(A_REVERSE);
  520. if (S_ISDIR(ent->mode))
  521. printw("%s%-17.17s / %s/\n",
  522. CURSYM(active), buf, ent->name);
  523. else if (S_ISLNK(ent->mode))
  524. printw("%s%-17.17s @ %s@\n",
  525. CURSYM(active), buf, ent->name);
  526. else if (S_ISSOCK(ent->mode))
  527. printw("%s%-17.17s = %s=\n",
  528. CURSYM(active), buf, ent->name);
  529. else if (S_ISFIFO(ent->mode))
  530. printw("%s%-17.17s | %s|\n",
  531. CURSYM(active), buf, ent->name);
  532. else if (S_ISBLK(ent->mode))
  533. printw("%s%-17.17s b %s\n",
  534. CURSYM(active), buf, ent->name);
  535. else if (S_ISCHR(ent->mode))
  536. printw("%s%-17.17s c %s\n",
  537. CURSYM(active), buf, ent->name);
  538. else if (ent->mode & S_IXUSR)
  539. printw("%s%-17.17s %8.8s* %s*\n", CURSYM(active),
  540. buf, coolsize(ent->size), ent->name);
  541. else
  542. printw("%s%-17.17s %8.8s %s\n", CURSYM(active),
  543. buf, coolsize(ent->size), ent->name);
  544. if (active)
  545. attroff(A_REVERSE);
  546. }
  547. static int
  548. dentfill(char *path, struct entry **dents,
  549. int (*filter)(regex_t *, char *), regex_t *re)
  550. {
  551. char newpath[PATH_MAX];
  552. DIR *dirp;
  553. struct dirent *dp;
  554. struct stat sb;
  555. int r, n = 0;
  556. dirp = opendir(path);
  557. if (dirp == NULL)
  558. return 0;
  559. while ((dp = readdir(dirp)) != NULL) {
  560. /* Skip self and parent */
  561. if (strcmp(dp->d_name, ".") == 0 ||
  562. strcmp(dp->d_name, "..") == 0)
  563. continue;
  564. if (filter(re, dp->d_name) == 0)
  565. continue;
  566. *dents = xrealloc(*dents, (n + 1) * sizeof(**dents));
  567. xstrlcpy((*dents)[n].name, dp->d_name, sizeof((*dents)[n].name));
  568. /* Get mode flags */
  569. mkpath(path, dp->d_name, newpath, sizeof(newpath));
  570. r = lstat(newpath, &sb);
  571. if (r == -1)
  572. printerr(1, "lstat");
  573. (*dents)[n].mode = sb.st_mode;
  574. (*dents)[n].t = sb.st_mtime;
  575. (*dents)[n].size = sb.st_size;
  576. n++;
  577. }
  578. /* Should never be null */
  579. r = closedir(dirp);
  580. if (r == -1)
  581. printerr(1, "closedir");
  582. return n;
  583. }
  584. static void
  585. dentfree(struct entry *dents)
  586. {
  587. free(dents);
  588. }
  589. /* Return the position of the matching entry or 0 otherwise */
  590. static int
  591. dentfind(struct entry *dents, int n, char *path)
  592. {
  593. if (!path)
  594. return 0;
  595. char *p = xmemrchr(path, '/', strlen(path));
  596. if (!p)
  597. p = path;
  598. else
  599. /* We are assuming an entry with actual
  600. name ending in '/' will not appear */
  601. p++;
  602. DPRINTF_S(p);
  603. for (int i = 0; i < n; i++)
  604. if (strcmp(p, dents[i].name) == 0)
  605. return i;
  606. return 0;
  607. }
  608. static int
  609. populate(char *path, char *oldpath, char *fltr)
  610. {
  611. regex_t re;
  612. int r;
  613. /* Can fail when permissions change while browsing */
  614. if (canopendir(path) == 0)
  615. return -1;
  616. /* Search filter */
  617. r = setfilter(&re, fltr);
  618. if (r != 0)
  619. return -1;
  620. dentfree(dents);
  621. ndents = 0;
  622. dents = NULL;
  623. ndents = dentfill(path, &dents, visible, &re);
  624. qsort(dents, ndents, sizeof(*dents), entrycmp);
  625. /* Find cur from history */
  626. cur = dentfind(dents, ndents, oldpath);
  627. return 0;
  628. }
  629. static void
  630. redraw(char *path)
  631. {
  632. static char cwd[PATH_MAX];
  633. static int nlines, odd;
  634. static int i;
  635. nlines = MIN(LINES - 4, ndents);
  636. /* Clean screen */
  637. erase();
  638. /* Strip trailing slashes */
  639. for (i = strlen(path) - 1; i > 0; i--)
  640. if (path[i] == '/')
  641. path[i] = '\0';
  642. else
  643. break;
  644. DPRINTF_D(cur);
  645. DPRINTF_S(path);
  646. /* No text wrapping in cwd line */
  647. if (!realpath(path, cwd)) {
  648. printmsg("Cannot resolve path");
  649. return;
  650. }
  651. printw(CWD "%s\n\n", cwd);
  652. /* Print listing */
  653. odd = ISODD(nlines);
  654. if (cur < (nlines >> 1)) {
  655. for (i = 0; i < nlines; i++)
  656. printptr(&dents[i], i == cur);
  657. } else if (cur >= ndents - (nlines >> 1)) {
  658. for (i = ndents - nlines; i < ndents; i++)
  659. printptr(&dents[i], i == cur);
  660. } else {
  661. nlines >>= 1;
  662. for (i = cur - nlines; i < cur + nlines + odd; i++)
  663. printptr(&dents[i], i == cur);
  664. }
  665. if (showdetail) {
  666. if (ndents) {
  667. static char ind[2] = "\0\0";
  668. static char sort[9];
  669. if (mtimeorder)
  670. sprintf(sort, "by time ");
  671. else if (sizeorder)
  672. sprintf(sort, "by size ");
  673. else
  674. sort[0] = '\0';
  675. if (S_ISDIR(dents[cur].mode))
  676. ind[0] = '/';
  677. else if (S_ISLNK(dents[cur].mode))
  678. ind[0] = '@';
  679. else if (S_ISSOCK(dents[cur].mode))
  680. ind[0] = '=';
  681. else if (S_ISFIFO(dents[cur].mode))
  682. ind[0] = '|';
  683. else if (dents[cur].mode & S_IXUSR)
  684. ind[0] = '*';
  685. else
  686. ind[0] = '\0';
  687. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  688. dents[cur].name, ind);
  689. printmsg(cwd);
  690. } else
  691. printmsg("0 items");
  692. }
  693. }
  694. static void
  695. browse(char *ipath, char *ifilter)
  696. {
  697. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  698. static char fltr[LINE_MAX];
  699. char *bin, *dir, *tmp, *run, *env;
  700. struct stat sb;
  701. regex_t re;
  702. int r, fd;
  703. xstrlcpy(path, ipath, sizeof(path));
  704. xstrlcpy(fltr, ifilter, sizeof(fltr));
  705. oldpath[0] = '\0';
  706. newpath[0] = '\0';
  707. begin:
  708. r = populate(path, oldpath, fltr);
  709. if (r == -1) {
  710. printwarn();
  711. goto nochange;
  712. }
  713. for (;;) {
  714. redraw(path);
  715. nochange:
  716. switch (nextsel(&run, &env)) {
  717. case SEL_QUIT:
  718. dentfree(dents);
  719. return;
  720. case SEL_BACK:
  721. /* There is no going back */
  722. if (strcmp(path, "/") == 0 ||
  723. strcmp(path, ".") == 0 ||
  724. strchr(path, '/') == NULL) {
  725. printmsg("You are at /");
  726. goto nochange;
  727. }
  728. dir = xdirname(path);
  729. if (canopendir(dir) == 0) {
  730. printwarn();
  731. goto nochange;
  732. }
  733. /* Save history */
  734. xstrlcpy(oldpath, path, sizeof(oldpath));
  735. xstrlcpy(path, dir, sizeof(path));
  736. /* Reset filter */
  737. xstrlcpy(fltr, ifilter, sizeof(fltr));
  738. goto begin;
  739. case SEL_GOIN:
  740. /* Cannot descend in empty directories */
  741. if (ndents == 0)
  742. goto nochange;
  743. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  744. DPRINTF_S(newpath);
  745. /* Get path info */
  746. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  747. if (fd == -1) {
  748. printwarn();
  749. goto nochange;
  750. }
  751. r = fstat(fd, &sb);
  752. if (r == -1) {
  753. printwarn();
  754. close(fd);
  755. goto nochange;
  756. }
  757. close(fd);
  758. DPRINTF_U(sb.st_mode);
  759. switch (sb.st_mode & S_IFMT) {
  760. case S_IFDIR:
  761. if (canopendir(newpath) == 0) {
  762. printwarn();
  763. goto nochange;
  764. }
  765. xstrlcpy(path, newpath, sizeof(path));
  766. /* Reset filter */
  767. xstrlcpy(fltr, ifilter, sizeof(fltr));
  768. goto begin;
  769. case S_IFREG:
  770. {
  771. static char cmd[MAX_CMD_LEN];
  772. static char *runvi = "vi";
  773. static int status;
  774. static FILE *fp;
  775. /* If default mime opener is set, use it */
  776. if (opener) {
  777. snprintf(cmd, MAX_CMD_LEN,
  778. "%s \"%s\" > /dev/null 2>&1",
  779. opener, newpath);
  780. status = system(cmd);
  781. continue;
  782. }
  783. /* Try custom applications */
  784. bin = openwith(newpath);
  785. if (bin == NULL) {
  786. /* If a custom handler application is
  787. not set, open plain text files with
  788. vi, then try fallback_opener */
  789. snprintf(cmd, MAX_CMD_LEN,
  790. "file \"%s\"", newpath);
  791. fp = popen(cmd, "r");
  792. if (fp == NULL)
  793. goto nochange;
  794. if (fgets(cmd, MAX_CMD_LEN, fp) == NULL) {
  795. pclose(fp);
  796. goto nochange;
  797. }
  798. pclose(fp);
  799. if (strstr(cmd, "ASCII text") != NULL)
  800. bin = runvi;
  801. else if (fallback_opener) {
  802. snprintf(cmd, MAX_CMD_LEN,
  803. "%s \"%s\" > \
  804. /dev/null 2>&1",
  805. fallback_opener,
  806. newpath);
  807. status = system(cmd);
  808. continue;
  809. } else {
  810. printmsg("No association");
  811. goto nochange;
  812. }
  813. }
  814. exitcurses();
  815. spawn(bin, newpath, NULL);
  816. initcurses();
  817. continue;
  818. }
  819. default:
  820. printmsg("Unsupported file");
  821. goto nochange;
  822. }
  823. case SEL_FLTR:
  824. /* Read filter */
  825. printprompt("filter: ");
  826. tmp = readln();
  827. if (tmp == NULL)
  828. tmp = ifilter;
  829. /* Check and report regex errors */
  830. r = setfilter(&re, tmp);
  831. if (r != 0)
  832. goto nochange;
  833. xstrlcpy(fltr, tmp, sizeof(fltr));
  834. DPRINTF_S(fltr);
  835. /* Save current */
  836. if (ndents > 0)
  837. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  838. goto begin;
  839. case SEL_NEXT:
  840. if (cur < ndents - 1)
  841. cur++;
  842. else if (ndents)
  843. /* Roll over, set cursor to first entry */
  844. cur = 0;
  845. break;
  846. case SEL_PREV:
  847. if (cur > 0)
  848. cur--;
  849. else if (ndents)
  850. /* Roll over, set cursor to last entry */
  851. cur = ndents - 1;
  852. break;
  853. case SEL_PGDN:
  854. if (cur < ndents - 1)
  855. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  856. break;
  857. case SEL_PGUP:
  858. if (cur > 0)
  859. cur -= MIN((LINES - 4) / 2, cur);
  860. break;
  861. case SEL_HOME:
  862. cur = 0;
  863. break;
  864. case SEL_END:
  865. cur = ndents - 1;
  866. break;
  867. case SEL_CD:
  868. /* Read target dir */
  869. printprompt("chdir: ");
  870. tmp = readln();
  871. if (tmp == NULL) {
  872. clearprompt();
  873. goto nochange;
  874. }
  875. mkpath(path, tmp, newpath, sizeof(newpath));
  876. if (canopendir(newpath) == 0) {
  877. printwarn();
  878. goto nochange;
  879. }
  880. xstrlcpy(path, newpath, sizeof(path));
  881. /* Reset filter */
  882. xstrlcpy(fltr, ifilter, sizeof(fltr));
  883. DPRINTF_S(path);
  884. goto begin;
  885. case SEL_CDHOME:
  886. tmp = getenv("HOME");
  887. if (tmp == NULL) {
  888. clearprompt();
  889. goto nochange;
  890. }
  891. if (canopendir(tmp) == 0) {
  892. printwarn();
  893. goto nochange;
  894. }
  895. xstrlcpy(path, tmp, sizeof(path));
  896. /* Reset filter */
  897. xstrlcpy(fltr, ifilter, sizeof(fltr));
  898. DPRINTF_S(path);
  899. goto begin;
  900. case SEL_TOGGLEDOT:
  901. showhidden ^= 1;
  902. initfilter(showhidden, &ifilter);
  903. xstrlcpy(fltr, ifilter, sizeof(fltr));
  904. goto begin;
  905. case SEL_DETAIL:
  906. showdetail = !showdetail;
  907. showdetail ? (printptr = &printent_long)
  908. : (printptr = &printent);
  909. /* Save current */
  910. if (ndents > 0)
  911. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  912. goto begin;
  913. case SEL_FSIZE:
  914. sizeorder = !sizeorder;
  915. mtimeorder = 0;
  916. /* Save current */
  917. if (ndents > 0)
  918. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  919. goto begin;
  920. case SEL_MTIME:
  921. mtimeorder = !mtimeorder;
  922. sizeorder = 0;
  923. /* Save current */
  924. if (ndents > 0)
  925. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  926. goto begin;
  927. case SEL_REDRAW:
  928. /* Save current */
  929. if (ndents > 0)
  930. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  931. goto begin;
  932. case SEL_COPY:
  933. if (copier && ndents) {
  934. char abspath[PATH_MAX];
  935. if (strcmp(path, "/") == 0)
  936. snprintf(abspath, PATH_MAX, "/%s",
  937. dents[cur].name);
  938. else
  939. snprintf(abspath, PATH_MAX, "%s/%s",
  940. path, dents[cur].name);
  941. spawn(copier, abspath, NULL);
  942. printmsg(abspath);
  943. } else if (!copier)
  944. printmsg("NNN_COPIER is not set");
  945. goto nochange;
  946. case SEL_RUN:
  947. run = xgetenv(env, run);
  948. exitcurses();
  949. spawn(run, NULL, path);
  950. initcurses();
  951. /* Re-populate as directory content may have changed */
  952. goto begin;
  953. case SEL_RUNARG:
  954. run = xgetenv(env, run);
  955. exitcurses();
  956. spawn(run, dents[cur].name, path);
  957. initcurses();
  958. break;
  959. }
  960. /* Screensaver */
  961. if (idletimeout != 0 && idle == idletimeout) {
  962. idle = 0;
  963. exitcurses();
  964. spawn(idlecmd, NULL, NULL);
  965. initcurses();
  966. }
  967. }
  968. }
  969. static void
  970. usage(void)
  971. {
  972. fprintf(stderr, "usage: nnn [-d] [dir]\n");
  973. exit(1);
  974. }
  975. int
  976. main(int argc, char *argv[])
  977. {
  978. char cwd[PATH_MAX], *ipath;
  979. char *ifilter;
  980. int opt = 0;
  981. /* Confirm we are in a terminal */
  982. if (!isatty(0) || !isatty(1)) {
  983. fprintf(stderr, "stdin or stdout is not a tty\n");
  984. exit(1);
  985. }
  986. if (argc > 3)
  987. usage();
  988. while ((opt = getopt(argc, argv, "d")) != -1) {
  989. switch (opt) {
  990. case 'd':
  991. /* Open in detail mode, if set */
  992. showdetail = 1;
  993. printptr = &printent_long;
  994. break;
  995. default:
  996. usage();
  997. }
  998. }
  999. if (argc == optind) {
  1000. /* Start in the current directory */
  1001. ipath = getcwd(cwd, sizeof(cwd));
  1002. if (ipath == NULL)
  1003. ipath = "/";
  1004. } else {
  1005. ipath = realpath(argv[optind], cwd);
  1006. if (!ipath) {
  1007. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  1008. exit(1);
  1009. }
  1010. }
  1011. if (getuid() == 0)
  1012. showhidden = 1;
  1013. initfilter(showhidden, &ifilter);
  1014. /* Get the default desktop mime opener, if set */
  1015. opener = getenv("NNN_OPENER");
  1016. /* Get the fallback desktop mime opener, if set */
  1017. fallback_opener = getenv("NNN_FALLBACK_OPENER");
  1018. /* Get the default copier, if set */
  1019. copier = getenv("NNN_COPIER");
  1020. signal(SIGINT, SIG_IGN);
  1021. /* Test initial path */
  1022. if (canopendir(ipath) == 0) {
  1023. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1024. exit(1);
  1025. }
  1026. /* Set locale before curses setup */
  1027. setlocale(LC_ALL, "");
  1028. initcurses();
  1029. browse(ipath, ifilter);
  1030. exitcurses();
  1031. exit(0);
  1032. }