My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

nnn.c 40 KiB

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