My build of nnn with minor changes
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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