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.

10 anni fa
8 anni fa
8 anni fa
8 anni fa
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580
  1. /* See LICENSE file for copyright and license details. */
  2. #include <sys/stat.h>
  3. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  4. || defined(__APPLE__)
  5. # include <sys/types.h>
  6. #else
  7. # include <sys/sysmacros.h>
  8. #endif
  9. #include <sys/wait.h>
  10. #include <sys/statvfs.h>
  11. #include <sys/resource.h>
  12. #include <ctype.h>
  13. #include <curses.h>
  14. #include <dirent.h>
  15. #include <errno.h>
  16. #include <fcntl.h>
  17. #include <grp.h>
  18. #include <libgen.h>
  19. #include <limits.h>
  20. #ifdef __gnu_hurd__
  21. #define PATH_MAX 4096
  22. #endif
  23. #include <locale.h>
  24. #include <pwd.h>
  25. #include <regex.h>
  26. #include <signal.h>
  27. #include <stdarg.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <time.h>
  32. #include <unistd.h>
  33. #include <wchar.h>
  34. #include <readline/readline.h>
  35. #ifndef __USE_XOPEN_EXTENDED
  36. #define __USE_XOPEN_EXTENDED 1
  37. #endif
  38. #include <ftw.h>
  39. #include "config.h"
  40. #ifdef DEBUGMODE
  41. static int DEBUG_FD;
  42. static int
  43. xprintf(int fd, const char *fmt, ...)
  44. {
  45. char buf[BUFSIZ];
  46. int r;
  47. va_list ap;
  48. va_start(ap, fmt);
  49. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  50. if (r > 0)
  51. r = write(fd, buf, r);
  52. va_end(ap);
  53. return r;
  54. }
  55. static int
  56. enabledbg()
  57. {
  58. FILE *fp = fopen("/tmp/nnn_debug", "w");
  59. if (!fp) {
  60. fprintf(stderr, "Cannot open debug file\n");
  61. return -1;
  62. }
  63. DEBUG_FD = fileno(fp);
  64. if (DEBUG_FD == -1) {
  65. fprintf(stderr, "Cannot open debug file descriptor\n");
  66. return -1;
  67. }
  68. return 0;
  69. }
  70. static void
  71. disabledbg()
  72. {
  73. close(DEBUG_FD);
  74. }
  75. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  76. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  77. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  78. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=0x%p\n", x)
  79. #else
  80. #define DPRINTF_D(x)
  81. #define DPRINTF_U(x)
  82. #define DPRINTF_S(x)
  83. #define DPRINTF_P(x)
  84. #endif /* DEBUGMODE */
  85. /* Macro definitions */
  86. #define VERSION "1.2"
  87. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  88. #undef MIN
  89. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  90. #define ISODD(x) ((x) & 1)
  91. #define TOUPPER(ch) \
  92. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  93. #define MAX_CMD_LEN 5120
  94. #define CWD "cwd: "
  95. #define CURSR " > "
  96. #define EMPTY " "
  97. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  98. #define FILTER '/'
  99. #define MAX_BM 10
  100. /* Macros to define process spawn behaviour as flags */
  101. #define F_NONE 0x00 /* no flag set */
  102. #define F_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
  103. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  104. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  105. #define F_SIGINT 0x08 /* restore default SIGINT handler */
  106. #define F_NORMAL 0x80 /* spawn child process in non-curses regular mode */
  107. typedef unsigned long ulong;
  108. typedef unsigned int uint;
  109. typedef unsigned char uchar;
  110. /* Directory entry */
  111. typedef struct entry {
  112. char name[NAME_MAX];
  113. mode_t mode;
  114. time_t t;
  115. off_t size;
  116. blkcnt_t blocks; /* number of 512B blocks allocated */
  117. } *pEntry;
  118. /* Bookmark */
  119. typedef struct {
  120. char *key;
  121. char *loc;
  122. } bm;
  123. /* Settings */
  124. typedef struct {
  125. uchar filtermode : 1; /* Set to enter filter mode */
  126. uchar mtimeorder : 1; /* Set to sort by time modified */
  127. uchar sizeorder : 1; /* Set to sort by file size */
  128. uchar blkorder : 1; /* Set to sort by blocks used (disk usage) */
  129. uchar showhidden : 1; /* Set to show hidden files */
  130. uchar showdetail : 1; /* Clear to show fewer file info */
  131. uchar showcolor : 1; /* Set to show dirs in blue */
  132. uchar dircolor : 1; /* Current status of dir color */
  133. } settings;
  134. /* Externs */
  135. #ifdef __APPLE__
  136. extern int add_history(const char *string);
  137. #else
  138. extern void add_history(const char *string);
  139. #endif
  140. extern int wget_wch(WINDOW *win, wint_t *wch);
  141. /* Globals */
  142. /* Configuration */
  143. static settings cfg = {0, 0, 0, 0, 0, 1, 1, 0};
  144. static struct entry *dents;
  145. static int ndents, cur, total_dents;
  146. static uint idle;
  147. static uint idletimeout;
  148. static char *player;
  149. static char *copier;
  150. static char *editor;
  151. static char *desktop_manager;
  152. static blkcnt_t ent_blocks;
  153. static blkcnt_t dir_blocks;
  154. static ulong num_files;
  155. static size_t fs_free;
  156. static uint open_max;
  157. static bm bookmark[MAX_BM];
  158. static const double div_2_pow_10 = 1.0 / 1024.0;
  159. static uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
  160. static uchar color = 4;
  161. /* Utilities to open files, run actions */
  162. static char * const utils[] = {
  163. #ifdef __APPLE__
  164. "/usr/bin/open",
  165. #else
  166. "/usr/bin/xdg-open",
  167. #endif
  168. "nlay",
  169. "mediainfo",
  170. "exiftool"
  171. };
  172. static char *metaviewer;
  173. /* For use in functions which are isolated and don't return the buffer */
  174. static char g_buf[MAX_CMD_LEN];
  175. /* Common message strings */
  176. static char *STR_NFTWFAIL = "nftw(3) failed";
  177. static char *STR_ATROOT = "You are at /";
  178. static char *STR_NOHOME = "HOME not set";
  179. /*
  180. * Layout:
  181. * .---------
  182. * | cwd: /mnt/path
  183. * |
  184. * | file0
  185. * | file1
  186. * | > file2
  187. * | file3
  188. * | file4
  189. * ...
  190. * | filen
  191. * |
  192. * | Permission denied
  193. * '------
  194. */
  195. /* Forward declarations */
  196. static void printmsg(char *);
  197. static void printwarn(void);
  198. static void printerr(int, char *);
  199. static void redraw(char *path);
  200. /* Functions */
  201. /* Increase the limit on open file descriptors, if possible */
  202. static rlim_t
  203. max_openfds()
  204. {
  205. struct rlimit rl;
  206. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  207. if (limit != 0)
  208. return 32;
  209. limit = rl.rlim_cur;
  210. rl.rlim_cur = rl.rlim_max;
  211. if (setrlimit(RLIMIT_NOFILE, &rl) == 0)
  212. return rl.rlim_max - 64;
  213. if (limit > 128)
  214. return limit - 64;
  215. return 32;
  216. }
  217. /*
  218. * Custom xstrlen()
  219. */
  220. static size_t
  221. xstrlen(const char *s)
  222. {
  223. static size_t len;
  224. if (!s)
  225. return 0;
  226. len = 0;
  227. while (*s)
  228. ++len, ++s;
  229. return len;
  230. }
  231. /*
  232. * Just a safe strncpy(3)
  233. * Always null ('\0') terminates if both src and dest are valid pointers.
  234. * Returns the number of bytes copied including terminating null byte.
  235. */
  236. static size_t
  237. xstrlcpy(char *dest, const char *src, size_t n)
  238. {
  239. static size_t len, blocks;
  240. if (!src || !dest)
  241. return 0;
  242. len = xstrlen(src) + 1;
  243. if (n > len)
  244. n = len;
  245. else if (len > n)
  246. /* Save total number of bytes to copy in len */
  247. len = n;
  248. blocks = n >> _WSHIFT;
  249. n -= (blocks << _WSHIFT);
  250. if (blocks) {
  251. static ulong *s, *d;
  252. s = (ulong *)src;
  253. d = (ulong *)dest;
  254. while (blocks) {
  255. *d = *s;
  256. ++d, ++s;
  257. --blocks;
  258. }
  259. if (!n) {
  260. dest = (char *)d;
  261. *--dest = '\0';
  262. return len;
  263. }
  264. src = (char *)s;
  265. dest = (char *)d;
  266. }
  267. while (--n && (*dest = *src))
  268. ++dest, ++src;
  269. if (!n)
  270. *dest = '\0';
  271. return len;
  272. }
  273. /*
  274. * Custom strcmp(), just what we need.
  275. * Returns 0 if same, else -1
  276. */
  277. static int
  278. xstrcmp(const char *s1, const char *s2)
  279. {
  280. if (!s1 || !s2)
  281. return -1;
  282. while (*s1 && *s1 == *s2)
  283. ++s1, ++s2;
  284. if (*s1 != *s2)
  285. return -1;
  286. return 0;
  287. }
  288. /*
  289. * The poor man's implementation of memrchr(3).
  290. * We are only looking for '/' in this program.
  291. */
  292. static void *
  293. xmemrchr(const void *s, uchar ch, size_t n)
  294. {
  295. if (!s || !n)
  296. return NULL;
  297. static uchar *p;
  298. p = (uchar *)s + n - 1;
  299. while (n) {
  300. if (*p == ch)
  301. return p;
  302. --p;
  303. --n;
  304. }
  305. return NULL;
  306. }
  307. /*
  308. * The following dirname(3) implementation does not
  309. * modify the input. We use a copy of the original.
  310. *
  311. * Modified from the glibc (GNU LGPL) version.
  312. */
  313. static char *
  314. xdirname(const char *path)
  315. {
  316. static char *buf = g_buf;
  317. static char *last_slash;
  318. xstrlcpy(buf, path, PATH_MAX);
  319. /* Find last '/'. */
  320. last_slash = strrchr(buf, '/');
  321. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  322. /* Determine whether all remaining characters are slashes. */
  323. char *runp;
  324. for (runp = last_slash; runp != buf; --runp)
  325. if (runp[-1] != '/')
  326. break;
  327. /* The '/' is the last character, we have to look further. */
  328. if (runp != buf)
  329. last_slash = xmemrchr(buf, '/', runp - buf);
  330. }
  331. if (last_slash != NULL) {
  332. /* Determine whether all remaining characters are slashes. */
  333. char *runp;
  334. for (runp = last_slash; runp != buf; --runp)
  335. if (runp[-1] != '/')
  336. break;
  337. /* Terminate the buffer. */
  338. if (runp == buf) {
  339. /* The last slash is the first character in the string.
  340. * We have to return "/". As a special case we have to
  341. * return "//" if there are exactly two slashes at the
  342. * beginning of the string. See XBD 4.10 Path Name
  343. * Resolution for more information.
  344. */
  345. if (last_slash == buf + 1)
  346. ++last_slash;
  347. else
  348. last_slash = buf + 1;
  349. } else
  350. last_slash = runp;
  351. last_slash[0] = '\0';
  352. } else {
  353. /* This assignment is ill-designed but the XPG specs require to
  354. * return a string containing "." in any case no directory part
  355. * is found and so a static and constant string is required.
  356. */
  357. buf[0] = '.';
  358. buf[1] = '\0';
  359. }
  360. return buf;
  361. }
  362. /*
  363. * Return number of dots if all chars in a string are dots, else 0
  364. */
  365. static int
  366. all_dots(const char *ptr)
  367. {
  368. if (!ptr)
  369. return FALSE;
  370. int count = 0;
  371. while (*ptr == '.')
  372. ++count, ++ptr;
  373. if (*ptr)
  374. return 0;
  375. return count;
  376. }
  377. /* Initialize curses mode */
  378. static void
  379. initcurses(void)
  380. {
  381. if (initscr() == NULL) {
  382. char *term = getenv("TERM");
  383. if (term != NULL)
  384. fprintf(stderr, "error opening TERM: %s\n", term);
  385. else
  386. fprintf(stderr, "initscr() failed\n");
  387. exit(1);
  388. }
  389. cbreak();
  390. noecho();
  391. nonl();
  392. intrflush(stdscr, FALSE);
  393. keypad(stdscr, TRUE);
  394. curs_set(FALSE); /* Hide cursor */
  395. start_color();
  396. use_default_colors();
  397. if (cfg.showcolor)
  398. init_pair(1, color, -1);
  399. timeout(1000); /* One second */
  400. }
  401. /*
  402. * Spawns a child process. Behaviour can be controlled using flag.
  403. * Limited to 2 arguments to a program, flag works on bit set.
  404. */
  405. static void
  406. spawn(char *file, char *arg1, char *arg2, char *dir, uchar flag)
  407. {
  408. pid_t pid;
  409. int status;
  410. if (flag & F_NORMAL)
  411. endwin();
  412. pid = fork();
  413. if (pid == 0) {
  414. if (dir != NULL)
  415. status = chdir(dir);
  416. /* Show a marker (to indicate nnn spawned shell) */
  417. if (flag & F_MARKER) {
  418. printf("\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  419. printf("Spawned shell level: %d\n",
  420. atoi(getenv("SHLVL")) + 1);
  421. }
  422. /* Suppress stdout and stderr */
  423. if (flag & F_NOTRACE) {
  424. int fd = open("/dev/null", O_WRONLY, 0200);
  425. dup2(fd, 1);
  426. dup2(fd, 2);
  427. close(fd);
  428. }
  429. if (flag & F_SIGINT)
  430. signal(SIGINT, SIG_DFL);
  431. execlp(file, file, arg1, arg2, NULL);
  432. _exit(1);
  433. } else {
  434. if (!(flag & F_NOWAIT))
  435. /* Ignore interruptions */
  436. while (waitpid(pid, &status, 0) == -1)
  437. DPRINTF_D(status);
  438. DPRINTF_D(pid);
  439. if (flag & F_NORMAL)
  440. initcurses();
  441. }
  442. }
  443. /* Get program name from env var, else return fallback program */
  444. static char *
  445. xgetenv(char *name, char *fallback)
  446. {
  447. if (name == NULL)
  448. return fallback;
  449. char *value = getenv(name);
  450. return value && value[0] ? value : fallback;
  451. }
  452. /*
  453. * We assume none of the strings are NULL.
  454. *
  455. * Let's have the logic to sort numeric names in numeric order.
  456. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  457. *
  458. * If the absolute numeric values are same, we fallback to alphasort.
  459. */
  460. static int
  461. xstricmp(char *s1, char *s2)
  462. {
  463. static char *c1, *c2;
  464. c1 = s1;
  465. while (isspace(*c1))
  466. ++c1;
  467. if (*c1 == '-' || *c1 == '+')
  468. ++c1;
  469. while (*c1 >= '0' && *c1 <= '9')
  470. ++c1;
  471. c2 = s2;
  472. while (isspace(*c2))
  473. ++c2;
  474. if (*c2 == '-' || *c2 == '+')
  475. ++c2;
  476. while (*c2 >= '0' && *c2 <= '9')
  477. ++c2;
  478. if (*c1 == '\0' && *c2 == '\0') {
  479. static long long num1, num2;
  480. num1 = strtoll(s1, &c1, 10);
  481. num2 = strtoll(s2, &c2, 10);
  482. if (num1 != num2) {
  483. if (num1 > num2)
  484. return 1;
  485. else
  486. return -1;
  487. }
  488. } else if (*c1 == '\0' && *c2 != '\0')
  489. return -1;
  490. else if (*c1 != '\0' && *c2 == '\0')
  491. return 1;
  492. while (*s2 && *s1 && TOUPPER(*s1) == TOUPPER(*s2))
  493. ++s1, ++s2;
  494. /* In case of alphabetically same names, make sure
  495. * lower case one comes before upper case one
  496. */
  497. if (!*s1 && !*s2)
  498. return 1;
  499. return (int) (TOUPPER(*s1) - TOUPPER(*s2));
  500. }
  501. /* Trim all whitespace from both ends, / from end */
  502. static char *
  503. strstrip(char *s)
  504. {
  505. if (!s || !*s)
  506. return s;
  507. size_t len = xstrlen(s) - 1;
  508. while (len != 0 && (isspace(s[len]) || s[len] == '/'))
  509. --len;
  510. s[len + 1] = '\0';
  511. while (*s && isspace(*s))
  512. ++s;
  513. return s;
  514. }
  515. static char *
  516. getmime(char *file)
  517. {
  518. regex_t regex;
  519. uint i;
  520. static uint len = LEN(assocs);
  521. for (i = 0; i < len; ++i) {
  522. if (regcomp(&regex, assocs[i].regex,
  523. REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  524. continue;
  525. if (regexec(&regex, file, 0, NULL, 0) == 0)
  526. return assocs[i].mime;
  527. }
  528. return NULL;
  529. }
  530. static int
  531. setfilter(regex_t *regex, char *filter)
  532. {
  533. static size_t len;
  534. static int r;
  535. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  536. if (r != 0 && filter && filter[0] != '\0') {
  537. len = COLS;
  538. if (len > LINE_MAX)
  539. len = LINE_MAX;
  540. regerror(r, regex, g_buf, len);
  541. printmsg(g_buf);
  542. }
  543. return r;
  544. }
  545. static void
  546. initfilter(int dot, char **ifilter)
  547. {
  548. *ifilter = dot ? "." : "^[^.]";
  549. }
  550. static int
  551. visible(regex_t *regex, char *file)
  552. {
  553. return regexec(regex, file, 0, NULL, 0) == 0;
  554. }
  555. static int
  556. entrycmp(const void *va, const void *vb)
  557. {
  558. static pEntry pa, pb;
  559. pa = (pEntry)va;
  560. pb = (pEntry)vb;
  561. /* Sort directories first */
  562. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  563. return 1;
  564. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  565. return -1;
  566. /* Do the actual sorting */
  567. if (cfg.mtimeorder)
  568. return pb->t - pa->t;
  569. if (cfg.sizeorder) {
  570. if (pb->size > pa->size)
  571. return 1;
  572. else if (pb->size < pa->size)
  573. return -1;
  574. }
  575. if (cfg.blkorder) {
  576. if (pb->blocks > pa->blocks)
  577. return 1;
  578. else if (pb->blocks < pa->blocks)
  579. return -1;
  580. }
  581. return xstricmp(pa->name, pb->name);
  582. }
  583. /* Messages show up at the bottom */
  584. static void
  585. printmsg(char *msg)
  586. {
  587. mvprintw(LINES - 1, 0, "%s\n", msg);
  588. }
  589. /* Display warning as a message */
  590. static void
  591. printwarn(void)
  592. {
  593. printmsg(strerror(errno));
  594. }
  595. /* Kill curses and display error before exiting */
  596. static void
  597. printerr(int ret, char *prefix)
  598. {
  599. endwin();
  600. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  601. exit(ret);
  602. }
  603. /* Clear the last line */
  604. static void
  605. clearprompt(void)
  606. {
  607. printmsg("");
  608. }
  609. /* Print prompt on the last line */
  610. static void
  611. printprompt(char *str)
  612. {
  613. clearprompt();
  614. printw(str);
  615. }
  616. /* Returns SEL_* if key is bound and 0 otherwise.
  617. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  618. * The next keyboard input can be simulated by presel.
  619. */
  620. static int
  621. nextsel(char **run, char **env, int *presel)
  622. {
  623. static int c;
  624. static uchar i;
  625. static uint len = LEN(bindings);
  626. c = *presel;
  627. if (c == 0)
  628. c = getch();
  629. else
  630. *presel = 0;
  631. if (c == -1)
  632. ++idle;
  633. else
  634. idle = 0;
  635. for (i = 0; i < len; ++i)
  636. if (c == bindings[i].sym) {
  637. *run = bindings[i].run;
  638. *env = bindings[i].env;
  639. return bindings[i].act;
  640. }
  641. return 0;
  642. }
  643. static void
  644. dentcpy(struct entry *dst, struct entry *src)
  645. {
  646. xstrlcpy(dst->name, src->name, NAME_MAX);
  647. dst->mode = src->mode;
  648. dst->t = src->t;
  649. dst->size = src->size;
  650. dst->blocks = src->blocks;
  651. }
  652. /*
  653. * Move non-matching entries to the end
  654. */
  655. static void
  656. fill(struct entry **dents, int (*filter)(regex_t *, char *), regex_t *re)
  657. {
  658. static int count;
  659. for (count = 0; count < ndents; ++count) {
  660. if (filter(re, (*dents)[count].name) == 0) {
  661. if (count != --ndents) {
  662. static struct entry _dent;
  663. /* Copy count to tmp */
  664. dentcpy(&_dent, &(*dents)[count]);
  665. /* Copy ndents - 1 to count */
  666. dentcpy(&(*dents)[count], &(*dents)[ndents]);
  667. /* Copy tmp to ndents - 1 */
  668. dentcpy(&(*dents)[ndents], &_dent);
  669. --count;
  670. }
  671. continue;
  672. }
  673. }
  674. }
  675. static int
  676. matches(char *fltr)
  677. {
  678. static regex_t re;
  679. /* Search filter */
  680. if (setfilter(&re, fltr) != 0)
  681. return -1;
  682. fill(&dents, visible, &re);
  683. qsort(dents, ndents, sizeof(*dents), entrycmp);
  684. return 0;
  685. }
  686. static int
  687. readln(char *path)
  688. {
  689. static char ln[LINE_MAX << 2];
  690. static wchar_t wln[LINE_MAX];
  691. static wint_t ch[2] = {0};
  692. int r, total = ndents;
  693. int oldcur = cur;
  694. int len = 1;
  695. char *pln = ln + 1;
  696. memset(wln, 0, LINE_MAX << 2);
  697. wln[0] = FILTER;
  698. ln[0] = FILTER;
  699. ln[1] = '\0';
  700. cur = 0;
  701. timeout(-1);
  702. echo();
  703. curs_set(TRUE);
  704. printprompt(ln);
  705. while ((r = wget_wch(stdscr, ch)) != ERR)
  706. if (r == OK)
  707. switch (*ch) {
  708. case '\r': // with nonl(), this is ENTER key value
  709. if (len == 1) {
  710. cur = oldcur;
  711. goto end;
  712. }
  713. if (matches(pln) == -1)
  714. goto end;
  715. redraw(path);
  716. goto end;
  717. case 127: // handle DEL
  718. if (len == 1) {
  719. cur = oldcur;
  720. *ch = CONTROL('L');
  721. goto end;
  722. }
  723. wln[--len] = '\0';
  724. if (len == 1)
  725. cur = oldcur;
  726. wcstombs(ln, wln, LINE_MAX << 2);
  727. ndents = total;
  728. if (matches(pln) == -1) {
  729. printprompt(ln);
  730. continue;
  731. }
  732. redraw(path);
  733. printprompt(ln);
  734. break;
  735. case CONTROL('L'):
  736. if (len == 1)
  737. cur = oldcur; // fallthrough
  738. case CONTROL('Q'):
  739. goto end;
  740. default:
  741. /* Reset cur in case it's a repeat search */
  742. if (len == 1)
  743. cur = 0;
  744. wln[len] = (wchar_t)*ch;
  745. wln[++len] = '\0';
  746. wcstombs(ln, wln, LINE_MAX << 2);
  747. ndents = total;
  748. if (matches(pln) == -1)
  749. continue;
  750. redraw(path);
  751. printprompt(ln);
  752. }
  753. else
  754. switch (*ch) {
  755. case KEY_DC: // fallthrough
  756. case KEY_BACKSPACE:
  757. if (len == 1) {
  758. cur = oldcur;
  759. *ch = CONTROL('L');
  760. goto end;
  761. }
  762. wln[--len] = '\0';
  763. if (len == 1)
  764. cur = oldcur;
  765. wcstombs(ln, wln, LINE_MAX << 2);
  766. ndents = total;
  767. if (matches(pln) == -1)
  768. continue;
  769. redraw(path);
  770. printprompt(ln);
  771. break;
  772. case KEY_DOWN: // fallthrough
  773. case KEY_UP: // fallthrough
  774. case KEY_LEFT: // fallthrough
  775. case KEY_RIGHT: // fallthrough
  776. case KEY_F(2):
  777. if (len == 1)
  778. cur = oldcur; // fallthrough
  779. default:
  780. goto end;
  781. }
  782. end:
  783. noecho();
  784. curs_set(FALSE);
  785. timeout(1000);
  786. /* Return keys for navigation etc. */
  787. return *ch;
  788. }
  789. /*
  790. * Returns "dir/name or "/name"
  791. */
  792. static char *
  793. mkpath(char *dir, char *name, char *out, size_t n)
  794. {
  795. /* Handle absolute path */
  796. if (name[0] == '/')
  797. xstrlcpy(out, name, n);
  798. else {
  799. /* Handle root case */
  800. if (dir[0] == '/' && dir[1] == '\0')
  801. snprintf(out, n, "/%s", name);
  802. else
  803. snprintf(out, n, "%s/%s", dir, name);
  804. }
  805. return out;
  806. }
  807. static void
  808. parsebmstr(char *bms)
  809. {
  810. int i = 0;
  811. while (*bms && i < MAX_BM) {
  812. bookmark[i].key = bms;
  813. ++bms;
  814. while (*bms && *bms != ':')
  815. ++bms;
  816. if (!*bms) {
  817. bookmark[i].key = NULL;
  818. break;
  819. }
  820. *bms = '\0';
  821. bookmark[i].loc = ++bms;
  822. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  823. bookmark[i].key = NULL;
  824. break;
  825. }
  826. while (*bms && *bms != ';')
  827. ++bms;
  828. if (*bms)
  829. *bms = '\0';
  830. else
  831. break;
  832. ++bms;
  833. ++i;
  834. }
  835. }
  836. static char *
  837. readinput(void)
  838. {
  839. timeout(-1);
  840. echo();
  841. curs_set(TRUE);
  842. memset(g_buf, 0, LINE_MAX);
  843. wgetnstr(stdscr, g_buf, LINE_MAX - 1);
  844. noecho();
  845. curs_set(FALSE);
  846. timeout(1000);
  847. return g_buf[0] ? g_buf : NULL;
  848. }
  849. /*
  850. * Replace escape characters in a string with '?'
  851. */
  852. static char *
  853. unescape(const char *str)
  854. {
  855. static char buffer[PATH_MAX];
  856. static wchar_t wbuf[PATH_MAX];
  857. static wchar_t *buf;
  858. buffer[0] = '\0';
  859. buf = wbuf;
  860. /* Convert multi-byte to wide char */
  861. mbstowcs(wbuf, str, PATH_MAX);
  862. while (*buf) {
  863. if (*buf <= '\x1f' || *buf == '\x7f')
  864. *buf = '\?';
  865. ++buf;
  866. }
  867. /* Convert wide char to multi-byte */
  868. wcstombs(buffer, wbuf, PATH_MAX);
  869. return buffer;
  870. }
  871. static void
  872. printent(struct entry *ent, int sel)
  873. {
  874. static int ncols;
  875. if (PATH_MAX + 16 < COLS)
  876. ncols = PATH_MAX + 16;
  877. else
  878. ncols = COLS;
  879. if (S_ISDIR(ent->mode))
  880. snprintf(g_buf, ncols, "%s%s/", CURSYM(sel),
  881. unescape(ent->name));
  882. else if (S_ISLNK(ent->mode))
  883. snprintf(g_buf, ncols, "%s%s@", CURSYM(sel),
  884. unescape(ent->name));
  885. else if (S_ISSOCK(ent->mode))
  886. snprintf(g_buf, ncols, "%s%s=", CURSYM(sel),
  887. unescape(ent->name));
  888. else if (S_ISFIFO(ent->mode))
  889. snprintf(g_buf, ncols, "%s%s|", CURSYM(sel),
  890. unescape(ent->name));
  891. else if (ent->mode & 0100)
  892. snprintf(g_buf, ncols, "%s%s*", CURSYM(sel),
  893. unescape(ent->name));
  894. else
  895. snprintf(g_buf, ncols, "%s%s", CURSYM(sel),
  896. unescape(ent->name));
  897. /* Dirs are always shown on top */
  898. if (cfg.dircolor && !S_ISDIR(ent->mode)) {
  899. attroff(COLOR_PAIR(1) | A_BOLD);
  900. cfg.dircolor = 0;
  901. }
  902. printw("%s\n", g_buf);
  903. }
  904. static char *
  905. coolsize(off_t size)
  906. {
  907. static const char * const U = "BKMGTPEZY";
  908. static char size_buf[12]; /* Buffer to hold human readable size */
  909. static int i;
  910. static off_t tmp;
  911. static long double rem;
  912. i = 0;
  913. rem = 0;
  914. while (size > 1024) {
  915. tmp = size;
  916. size >>= 10;
  917. rem = tmp - (size << 10);
  918. ++i;
  919. }
  920. snprintf(size_buf, 12, "%.*Lf%c", i, size + rem * div_2_pow_10, U[i]);
  921. return size_buf;
  922. }
  923. static void
  924. printent_long(struct entry *ent, int sel)
  925. {
  926. static int ncols;
  927. static char buf[18];
  928. if (PATH_MAX + 32 < COLS)
  929. ncols = PATH_MAX + 32;
  930. else
  931. ncols = COLS;
  932. strftime(buf, 18, "%d %m %Y %H:%M", localtime(&ent->t));
  933. if (sel)
  934. attron(A_REVERSE);
  935. if (!cfg.blkorder) {
  936. if (S_ISDIR(ent->mode))
  937. snprintf(g_buf, ncols, "%s%-16.16s / %s/",
  938. CURSYM(sel), buf, unescape(ent->name));
  939. else if (S_ISLNK(ent->mode))
  940. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  941. CURSYM(sel), buf, unescape(ent->name));
  942. else if (S_ISSOCK(ent->mode))
  943. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  944. CURSYM(sel), buf, unescape(ent->name));
  945. else if (S_ISFIFO(ent->mode))
  946. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  947. CURSYM(sel), buf, unescape(ent->name));
  948. else if (S_ISBLK(ent->mode))
  949. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  950. CURSYM(sel), buf, unescape(ent->name));
  951. else if (S_ISCHR(ent->mode))
  952. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  953. CURSYM(sel), buf, unescape(ent->name));
  954. else if (ent->mode & 0100)
  955. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  956. CURSYM(sel), buf, coolsize(ent->size),
  957. unescape(ent->name));
  958. else
  959. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  960. CURSYM(sel), buf, coolsize(ent->size),
  961. unescape(ent->name));
  962. } else {
  963. if (S_ISDIR(ent->mode))
  964. snprintf(g_buf, ncols, "%s%-16.16s %8.8s/ %s/",
  965. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  966. unescape(ent->name));
  967. else if (S_ISLNK(ent->mode))
  968. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  969. CURSYM(sel), buf,
  970. unescape(ent->name));
  971. else if (S_ISSOCK(ent->mode))
  972. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  973. CURSYM(sel), buf,
  974. unescape(ent->name));
  975. else if (S_ISFIFO(ent->mode))
  976. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  977. CURSYM(sel), buf,
  978. unescape(ent->name));
  979. else if (S_ISBLK(ent->mode))
  980. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  981. CURSYM(sel), buf,
  982. unescape(ent->name));
  983. else if (S_ISCHR(ent->mode))
  984. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  985. CURSYM(sel), buf,
  986. unescape(ent->name));
  987. else if (ent->mode & 0100)
  988. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  989. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  990. unescape(ent->name));
  991. else
  992. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  993. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  994. unescape(ent->name));
  995. }
  996. /* Dirs are always shown on top */
  997. if (cfg.dircolor && !S_ISDIR(ent->mode)) {
  998. attroff(COLOR_PAIR(1) | A_BOLD);
  999. cfg.dircolor = 0;
  1000. }
  1001. printw("%s\n", g_buf);
  1002. if (sel)
  1003. attroff(A_REVERSE);
  1004. }
  1005. static void (*printptr)(struct entry *ent, int sel) = &printent_long;
  1006. static char
  1007. get_fileind(mode_t mode, char *desc)
  1008. {
  1009. static char c;
  1010. if (S_ISREG(mode)) {
  1011. c = '-';
  1012. sprintf(desc, "%s", "regular file");
  1013. if (mode & 0100)
  1014. strcat(desc, ", executable");
  1015. } else if (S_ISDIR(mode)) {
  1016. c = 'd';
  1017. sprintf(desc, "%s", "directory");
  1018. } else if (S_ISBLK(mode)) {
  1019. c = 'b';
  1020. sprintf(desc, "%s", "block special device");
  1021. } else if (S_ISCHR(mode)) {
  1022. c = 'c';
  1023. sprintf(desc, "%s", "character special device");
  1024. #ifdef S_ISFIFO
  1025. } else if (S_ISFIFO(mode)) {
  1026. c = 'p';
  1027. sprintf(desc, "%s", "FIFO");
  1028. #endif /* S_ISFIFO */
  1029. #ifdef S_ISLNK
  1030. } else if (S_ISLNK(mode)) {
  1031. c = 'l';
  1032. sprintf(desc, "%s", "symbolic link");
  1033. #endif /* S_ISLNK */
  1034. #ifdef S_ISSOCK
  1035. } else if (S_ISSOCK(mode)) {
  1036. c = 's';
  1037. sprintf(desc, "%s", "socket");
  1038. #endif /* S_ISSOCK */
  1039. #ifdef S_ISDOOR
  1040. /* Solaris 2.6, etc. */
  1041. } else if (S_ISDOOR(mode)) {
  1042. c = 'D';
  1043. desc[0] = '\0';
  1044. #endif /* S_ISDOOR */
  1045. } else {
  1046. /* Unknown type -- possibly a regular file? */
  1047. c = '?';
  1048. desc[0] = '\0';
  1049. }
  1050. return c;
  1051. }
  1052. /* Convert a mode field into "ls -l" type perms field. */
  1053. static char *
  1054. get_lsperms(mode_t mode, char *desc)
  1055. {
  1056. static const char * const rwx[] = {"---", "--x", "-w-", "-wx",
  1057. "r--", "r-x", "rw-", "rwx"};
  1058. static char bits[11];
  1059. bits[0] = get_fileind(mode, desc);
  1060. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  1061. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  1062. strcpy(&bits[7], rwx[(mode & 7)]);
  1063. if (mode & S_ISUID)
  1064. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1065. if (mode & S_ISGID)
  1066. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1067. if (mode & S_ISVTX)
  1068. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1069. bits[10] = '\0';
  1070. return bits;
  1071. }
  1072. /*
  1073. * Gets only a single line (that's what we need
  1074. * for now) or shows full command output in pager.
  1075. *
  1076. * If pager is valid, returns NULL
  1077. */
  1078. static char *
  1079. get_output(char *buf, size_t bytes, char *file,
  1080. char *arg1, char *arg2, int pager)
  1081. {
  1082. pid_t pid;
  1083. int pipefd[2];
  1084. FILE *pf;
  1085. int tmp, flags;
  1086. char *ret = NULL;
  1087. if (pipe(pipefd) == -1)
  1088. printerr(1, "pipe(2)");
  1089. for (tmp = 0; tmp < 2; ++tmp) {
  1090. /* Get previous flags */
  1091. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1092. /* Set bit for non-blocking flag */
  1093. flags |= O_NONBLOCK;
  1094. /* Change flags on fd */
  1095. fcntl(pipefd[tmp], F_SETFL, flags);
  1096. }
  1097. pid = fork();
  1098. if (pid == 0) {
  1099. /* In child */
  1100. close(pipefd[0]);
  1101. dup2(pipefd[1], STDOUT_FILENO);
  1102. dup2(pipefd[1], STDERR_FILENO);
  1103. close(pipefd[1]);
  1104. execlp(file, file, arg1, arg2, NULL);
  1105. _exit(1);
  1106. }
  1107. /* In parent */
  1108. waitpid(pid, &tmp, 0);
  1109. close(pipefd[1]);
  1110. if (!pager) {
  1111. pf = fdopen(pipefd[0], "r");
  1112. if (pf) {
  1113. ret = fgets(buf, bytes, pf);
  1114. close(pipefd[0]);
  1115. }
  1116. return ret;
  1117. }
  1118. pid = fork();
  1119. if (pid == 0) {
  1120. /* Show in pager in child */
  1121. dup2(pipefd[0], STDIN_FILENO);
  1122. close(pipefd[0]);
  1123. execlp("less", "less", NULL);
  1124. _exit(1);
  1125. }
  1126. /* In parent */
  1127. waitpid(pid, &tmp, 0);
  1128. close(pipefd[0]);
  1129. return NULL;
  1130. }
  1131. /*
  1132. * Follows the stat(1) output closely
  1133. */
  1134. static int
  1135. show_stats(char *fpath, char *fname, struct stat *sb)
  1136. {
  1137. char *perms = get_lsperms(sb->st_mode, g_buf);
  1138. char *p, *begin = g_buf;
  1139. char tmp[] = "/tmp/nnnXXXXXX";
  1140. int fd = mkstemp(tmp);
  1141. if (fd == -1)
  1142. return -1;
  1143. /* Show file name or 'symlink' -> 'target' */
  1144. if (perms[0] == 'l') {
  1145. /* Note that MAX_CMD_LEN > PATH_MAX */
  1146. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1147. if (len != -1) {
  1148. g_buf[len] = '\0';
  1149. dprintf(fd, " File: '%s' -> ", unescape(fname));
  1150. dprintf(fd, "'%s'", unescape(g_buf));
  1151. xstrlcpy(g_buf, "symbolic link", MAX_CMD_LEN);
  1152. }
  1153. } else
  1154. dprintf(fd, " File: '%s'", unescape(fname));
  1155. /* Show size, blocks, file type */
  1156. #ifdef __APPLE__
  1157. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1158. #else
  1159. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1160. #endif
  1161. sb->st_size, sb->st_blocks, sb->st_blksize, g_buf);
  1162. /* Show containing device, inode, hardlink count */
  1163. #ifdef __APPLE__
  1164. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1165. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1166. #else
  1167. sprintf(g_buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  1168. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1169. #endif
  1170. g_buf, sb->st_ino, sb->st_nlink);
  1171. /* Show major, minor number for block or char device */
  1172. if (perms[0] == 'b' || perms[0] == 'c')
  1173. dprintf(fd, " Device type: %x,%x",
  1174. major(sb->st_rdev), minor(sb->st_rdev));
  1175. /* Show permissions, owner, group */
  1176. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)",
  1177. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7, sb->st_mode & 7,
  1178. perms,
  1179. sb->st_uid, (getpwuid(sb->st_uid))->pw_name,
  1180. sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1181. /* Show last access time */
  1182. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1183. dprintf(fd, "\n\n Access: %s", g_buf);
  1184. /* Show last modification time */
  1185. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1186. dprintf(fd, "\n Modify: %s", g_buf);
  1187. /* Show last status change time */
  1188. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1189. dprintf(fd, "\n Change: %s", g_buf);
  1190. if (S_ISREG(sb->st_mode)) {
  1191. /* Show file(1) output */
  1192. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1193. if (p) {
  1194. dprintf(fd, "\n\n ");
  1195. while (*p) {
  1196. if (*p == ',') {
  1197. *p = '\0';
  1198. dprintf(fd, " %s\n", begin);
  1199. begin = p + 1;
  1200. }
  1201. ++p;
  1202. }
  1203. dprintf(fd, " %s", begin);
  1204. }
  1205. dprintf(fd, "\n\n");
  1206. } else
  1207. dprintf(fd, "\n\n\n");
  1208. close(fd);
  1209. endwin();
  1210. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1211. unlink(tmp);
  1212. initcurses();
  1213. return 0;
  1214. }
  1215. static int
  1216. show_mediainfo(char *fpath, char *arg)
  1217. {
  1218. if (!get_output(g_buf, MAX_CMD_LEN, "which", metaviewer, NULL, 0))
  1219. return -1;
  1220. endwin();
  1221. get_output(NULL, 0, metaviewer, fpath, arg, 1);
  1222. initcurses();
  1223. return 0;
  1224. }
  1225. static int
  1226. show_help(void)
  1227. {
  1228. char tmp[] = "/tmp/nnnXXXXXX";
  1229. static char helpstr[] = ("\
  1230. Key | Function\n\
  1231. -+-\n\
  1232. ↑, k, ^P | Previous entry\n\
  1233. ↓, j, ^N | Next entry\n\
  1234. PgUp, ^U | Scroll half page up\n\
  1235. PgDn, ^D | Scroll half page down\n\
  1236. Home, g, ^, ^A | Jump to first entry\n\
  1237. End, G, $, ^E | Jump to last entry\n\
  1238. →, ↵, l, ^M | Open file or enter dir\n\
  1239. ←, Bksp, h, ^H | Go to parent dir\n\
  1240. Insert | Toggle navigate-as-you-type\n\
  1241. ~ | Jump to HOME dir\n\
  1242. & | Jump to initial dir\n\
  1243. - | Jump to last visited dir\n\
  1244. / | Filter dir contents\n\
  1245. ^/ | Open desktop search tool\n\
  1246. . | Toggle hide .dot files\n\
  1247. b | Show bookmark key prompt\n\
  1248. c | Show change dir prompt\n\
  1249. d | Toggle detail view\n\
  1250. D | Show current file details\n\
  1251. m | Show concise media info\n\
  1252. M | Show full media info\n\
  1253. s | Toggle sort by file size\n\
  1254. S | Toggle disk usage mode\n\
  1255. t | Toggle sort by mtime\n\
  1256. ! | Spawn SHELL in current dir\n\
  1257. e | Edit entry in EDITOR\n\
  1258. o | Open dir in file manager\n\
  1259. p | Open entry in PAGER\n\
  1260. ^K | Invoke file path copier\n\
  1261. ^L, F2 | Force a redraw, unfilter\n\
  1262. ? | Show help, settings\n\
  1263. Q | Quit and change dir\n\
  1264. q, ^Q | Quit\n\n");
  1265. int i = 0, fd = mkstemp(tmp);
  1266. if (fd == -1)
  1267. return -1;
  1268. dprintf(fd, "%s", helpstr);
  1269. if (getenv("NNN_BMS")) {
  1270. dprintf(fd, "BOOKMARKS\n");
  1271. for (; i < MAX_BM; ++i)
  1272. if (bookmark[i].key)
  1273. dprintf(fd, "\t%s: %s\n",
  1274. bookmark[i].key, bookmark[i].loc);
  1275. else
  1276. break;
  1277. dprintf(fd, "\n");
  1278. }
  1279. if (editor)
  1280. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1281. if (desktop_manager)
  1282. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1283. if (idletimeout)
  1284. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1285. if (copier)
  1286. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1287. dprintf(fd, "\n");
  1288. close(fd);
  1289. endwin();
  1290. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1291. unlink(tmp);
  1292. initcurses();
  1293. return 0;
  1294. }
  1295. static int
  1296. sum_bsizes(const char *fpath, const struct stat *sb,
  1297. int typeflag, struct FTW *ftwbuf)
  1298. {
  1299. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1300. ent_blocks += sb->st_blocks;
  1301. ++num_files;
  1302. return 0;
  1303. }
  1304. static int
  1305. getorder(size_t size)
  1306. {
  1307. switch (size) {
  1308. case 4096:
  1309. return 12;
  1310. case 512:
  1311. return 9;
  1312. case 8192:
  1313. return 13;
  1314. case 16384:
  1315. return 14;
  1316. case 32768:
  1317. return 15;
  1318. case 65536:
  1319. return 16;
  1320. case 131072:
  1321. return 17;
  1322. case 262144:
  1323. return 18;
  1324. case 524288:
  1325. return 19;
  1326. case 1048576:
  1327. return 20;
  1328. case 2048:
  1329. return 11;
  1330. case 1024:
  1331. return 10;
  1332. default:
  1333. return 0;
  1334. }
  1335. }
  1336. static int
  1337. dentfill(char *path, struct entry **dents,
  1338. int (*filter)(regex_t *, char *), regex_t *re)
  1339. {
  1340. static DIR *dirp;
  1341. static struct dirent *dp;
  1342. static struct stat sb;
  1343. static int fd, n;
  1344. n = 0;
  1345. if (cfg.blkorder) {
  1346. num_files = 0;
  1347. dir_blocks = 0;
  1348. }
  1349. dirp = opendir(path);
  1350. if (dirp == NULL)
  1351. return 0;
  1352. fd = dirfd(dirp);
  1353. while ((dp = readdir(dirp)) != NULL) {
  1354. /* Skip self and parent */
  1355. if ((dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
  1356. (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))))
  1357. continue;
  1358. if (filter(re, dp->d_name) == 0) {
  1359. if (!cfg.blkorder)
  1360. continue;
  1361. if (fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW)
  1362. == -1)
  1363. continue;
  1364. if (S_ISDIR(sb.st_mode)) {
  1365. ent_blocks = 0;
  1366. mkpath(path, dp->d_name, g_buf, PATH_MAX);
  1367. if (nftw(g_buf, sum_bsizes, open_max,
  1368. FTW_MOUNT | FTW_PHYS) == -1) {
  1369. printmsg(STR_NFTWFAIL);
  1370. dir_blocks += sb.st_blocks;
  1371. } else
  1372. dir_blocks += ent_blocks;
  1373. } else {
  1374. if (sb.st_blocks)
  1375. dir_blocks += sb.st_blocks;
  1376. ++num_files;
  1377. }
  1378. continue;
  1379. }
  1380. if (fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1381. if (*dents)
  1382. free(*dents);
  1383. printerr(1, "fstatat");
  1384. }
  1385. if (n == total_dents) {
  1386. total_dents += 64;
  1387. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1388. if (*dents == NULL)
  1389. printerr(1, "realloc");
  1390. }
  1391. xstrlcpy((*dents)[n].name, dp->d_name, NAME_MAX);
  1392. (*dents)[n].mode = sb.st_mode;
  1393. (*dents)[n].t = sb.st_mtime;
  1394. (*dents)[n].size = sb.st_size;
  1395. if (cfg.blkorder) {
  1396. if (S_ISDIR(sb.st_mode)) {
  1397. ent_blocks = 0;
  1398. mkpath(path, dp->d_name, g_buf, PATH_MAX);
  1399. if (nftw(g_buf, sum_bsizes, open_max,
  1400. FTW_MOUNT | FTW_PHYS) == -1) {
  1401. printmsg(STR_NFTWFAIL);
  1402. (*dents)[n].blocks = sb.st_blocks;
  1403. } else
  1404. (*dents)[n].blocks = ent_blocks;
  1405. } else {
  1406. (*dents)[n].blocks = sb.st_blocks;
  1407. ++num_files;
  1408. }
  1409. if ((*dents)[n].blocks)
  1410. dir_blocks += (*dents)[n].blocks;
  1411. }
  1412. ++n;
  1413. }
  1414. if (cfg.blkorder) {
  1415. static struct statvfs svb;
  1416. if (statvfs(path, &svb) == -1)
  1417. fs_free = 0;
  1418. else
  1419. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1420. }
  1421. /* Should never be null */
  1422. if (closedir(dirp) == -1) {
  1423. if (*dents)
  1424. free(*dents);
  1425. printerr(1, "closedir");
  1426. }
  1427. return n;
  1428. }
  1429. static void
  1430. dentfree(struct entry *dents)
  1431. {
  1432. free(dents);
  1433. }
  1434. /* Return the position of the matching entry or 0 otherwise */
  1435. static int
  1436. dentfind(struct entry *dents, int n, char *path)
  1437. {
  1438. if (!path)
  1439. return 0;
  1440. static int i;
  1441. static char *p;
  1442. p = basename(path);
  1443. DPRINTF_S(p);
  1444. for (i = 0; i < n; ++i)
  1445. if (xstrcmp(p, dents[i].name) == 0)
  1446. return i;
  1447. return 0;
  1448. }
  1449. static int
  1450. populate(char *path, char *oldpath, char *fltr)
  1451. {
  1452. static regex_t re;
  1453. /* Can fail when permissions change while browsing */
  1454. if (access(path, R_OK) == -1)
  1455. return -1;
  1456. /* Search filter */
  1457. if (setfilter(&re, fltr) != 0)
  1458. return -1;
  1459. if (cfg.blkorder) {
  1460. printmsg("Calculating...");
  1461. refresh();
  1462. }
  1463. ndents = dentfill(path, &dents, visible, &re);
  1464. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1465. /* Find cur from history */
  1466. cur = dentfind(dents, ndents, oldpath);
  1467. return 0;
  1468. }
  1469. static void
  1470. redraw(char *path)
  1471. {
  1472. static int nlines, i;
  1473. static size_t ncols;
  1474. nlines = MIN(LINES - 4, ndents);
  1475. /* Clean screen */
  1476. erase();
  1477. /* Strip trailing slashes */
  1478. for (i = xstrlen(path) - 1; i > 0; --i)
  1479. if (path[i] == '/')
  1480. path[i] = '\0';
  1481. else
  1482. break;
  1483. DPRINTF_D(cur);
  1484. DPRINTF_S(path);
  1485. /* No text wrapping in cwd line */
  1486. if (!realpath(path, g_buf)) {
  1487. printmsg("Cannot resolve path");
  1488. return;
  1489. }
  1490. ncols = COLS;
  1491. if (ncols > PATH_MAX)
  1492. ncols = PATH_MAX;
  1493. /* - xstrlen(CWD) - 1 = 6 */
  1494. g_buf[ncols - 6] = '\0';
  1495. printw(CWD "%s\n\n", g_buf);
  1496. if (cfg.showcolor) {
  1497. attron(COLOR_PAIR(1) | A_BOLD);
  1498. cfg.dircolor = 1;
  1499. }
  1500. /* Print listing */
  1501. if (cur < (nlines >> 1)) {
  1502. for (i = 0; i < nlines; ++i)
  1503. printptr(&dents[i], i == cur);
  1504. } else if (cur >= ndents - (nlines >> 1)) {
  1505. for (i = ndents - nlines; i < ndents; ++i)
  1506. printptr(&dents[i], i == cur);
  1507. } else {
  1508. static int odd;
  1509. odd = ISODD(nlines);
  1510. nlines >>= 1;
  1511. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1512. printptr(&dents[i], i == cur);
  1513. }
  1514. /* Must reset e.g. no files in dir */
  1515. if (cfg.dircolor) {
  1516. attroff(COLOR_PAIR(1) | A_BOLD);
  1517. cfg.dircolor = 0;
  1518. }
  1519. if (cfg.showdetail) {
  1520. if (ndents) {
  1521. static char ind[2] = "\0\0";
  1522. static char sort[9];
  1523. if (cfg.mtimeorder)
  1524. sprintf(sort, "by time ");
  1525. else if (cfg.sizeorder)
  1526. sprintf(sort, "by size ");
  1527. else
  1528. sort[0] = '\0';
  1529. if (S_ISDIR(dents[cur].mode))
  1530. ind[0] = '/';
  1531. else if (S_ISLNK(dents[cur].mode))
  1532. ind[0] = '@';
  1533. else if (S_ISSOCK(dents[cur].mode))
  1534. ind[0] = '=';
  1535. else if (S_ISFIFO(dents[cur].mode))
  1536. ind[0] = '|';
  1537. else if (dents[cur].mode & 0100)
  1538. ind[0] = '*';
  1539. else
  1540. ind[0] = '\0';
  1541. /* We need to show filename as it may
  1542. * be truncated in directory listing
  1543. */
  1544. if (!cfg.blkorder)
  1545. sprintf(g_buf, "total %d %s[%s%s]", ndents,
  1546. sort, unescape(dents[cur].name), ind);
  1547. else {
  1548. i = sprintf(g_buf, "du: %s (%lu files) ",
  1549. coolsize(dir_blocks << 9),
  1550. num_files);
  1551. sprintf(g_buf + i, "vol: %s free [%s%s]",
  1552. coolsize(fs_free),
  1553. unescape(dents[cur].name), ind);
  1554. }
  1555. printmsg(g_buf);
  1556. } else
  1557. printmsg("0 items");
  1558. }
  1559. }
  1560. static void
  1561. browse(char *ipath, char *ifilter)
  1562. {
  1563. char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  1564. char lastdir[PATH_MAX];
  1565. char fltr[LINE_MAX];
  1566. char *dir, *tmp, *run, *env, *tgt = NULL;
  1567. struct stat sb;
  1568. int r, fd, presel;
  1569. enum action sel = SEL_RUNARG + 1;
  1570. xstrlcpy(path, ipath, PATH_MAX);
  1571. xstrlcpy(fltr, ifilter, LINE_MAX);
  1572. oldpath[0] = '\0';
  1573. newpath[0] = '\0';
  1574. lastdir[0] = '\0'; /* Can't move back from initial directory */
  1575. if (cfg.filtermode)
  1576. presel = FILTER;
  1577. else
  1578. presel = 0;
  1579. begin:
  1580. if (populate(path, oldpath, fltr) == -1) {
  1581. printwarn();
  1582. goto nochange;
  1583. }
  1584. for (;;) {
  1585. redraw(path);
  1586. nochange:
  1587. /* Exit if parent has exited */
  1588. if (getppid() == 1)
  1589. _exit(0);
  1590. sel = nextsel(&run, &env, &presel);
  1591. switch (sel) {
  1592. case SEL_CDQUIT:
  1593. {
  1594. char *tmpfile = "/tmp/nnn";
  1595. tmp = getenv("NNN_TMPFILE");
  1596. if (tmp)
  1597. tmpfile = tmp;
  1598. FILE *fp = fopen(tmpfile, "w");
  1599. if (fp) {
  1600. fprintf(fp, "cd \"%s\"", path);
  1601. fclose(fp);
  1602. }
  1603. /* Fall through to exit */
  1604. } // fallthrough
  1605. case SEL_QUIT:
  1606. dentfree(dents);
  1607. return;
  1608. case SEL_BACK:
  1609. /* There is no going back */
  1610. if (path[0] == '/' && path[1] == '\0') {
  1611. printmsg(STR_ATROOT);
  1612. goto nochange;
  1613. }
  1614. dir = xdirname(path);
  1615. if (access(dir, R_OK) == -1) {
  1616. printwarn();
  1617. goto nochange;
  1618. }
  1619. /* Save history */
  1620. xstrlcpy(oldpath, path, PATH_MAX);
  1621. /* Save last working directory */
  1622. xstrlcpy(lastdir, path, PATH_MAX);
  1623. xstrlcpy(path, dir, PATH_MAX);
  1624. /* Reset filter */
  1625. xstrlcpy(fltr, ifilter, LINE_MAX);
  1626. if (cfg.filtermode)
  1627. presel = FILTER;
  1628. goto begin;
  1629. case SEL_GOIN:
  1630. /* Cannot descend in empty directories */
  1631. if (ndents == 0)
  1632. goto begin;
  1633. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1634. DPRINTF_S(newpath);
  1635. /* Get path info */
  1636. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1637. if (fd == -1) {
  1638. printwarn();
  1639. goto nochange;
  1640. }
  1641. r = fstat(fd, &sb);
  1642. if (r == -1) {
  1643. printwarn();
  1644. close(fd);
  1645. goto nochange;
  1646. }
  1647. close(fd);
  1648. DPRINTF_U(sb.st_mode);
  1649. switch (sb.st_mode & S_IFMT) {
  1650. case S_IFDIR:
  1651. if (access(newpath, R_OK) == -1) {
  1652. printwarn();
  1653. goto nochange;
  1654. }
  1655. /* Save last working directory */
  1656. xstrlcpy(lastdir, path, PATH_MAX);
  1657. xstrlcpy(path, newpath, PATH_MAX);
  1658. oldpath[0] = '\0';
  1659. /* Reset filter */
  1660. xstrlcpy(fltr, ifilter, LINE_MAX);
  1661. if (cfg.filtermode)
  1662. presel = FILTER;
  1663. goto begin;
  1664. case S_IFREG:
  1665. {
  1666. /* If NNN_USE_EDITOR is set,
  1667. * open text in EDITOR
  1668. */
  1669. if (editor) {
  1670. if (getmime(dents[cur].name)) {
  1671. spawn(editor, newpath, NULL,
  1672. NULL, F_NORMAL);
  1673. continue;
  1674. }
  1675. /* Recognize and open plain
  1676. * text files with vi
  1677. */
  1678. if (get_output(g_buf, MAX_CMD_LEN,
  1679. "file", "-bi",
  1680. newpath, 0) == NULL)
  1681. continue;
  1682. if (strstr(g_buf, "text/") == g_buf) {
  1683. spawn(editor, newpath, NULL,
  1684. NULL, F_NORMAL);
  1685. continue;
  1686. }
  1687. }
  1688. /* Invoke desktop opener as last resort */
  1689. spawn(utils[0], newpath, NULL, NULL, F_NOTRACE);
  1690. continue;
  1691. }
  1692. default:
  1693. printmsg("Unsupported file");
  1694. goto nochange;
  1695. }
  1696. case SEL_FLTR:
  1697. presel = readln(path);
  1698. xstrlcpy(fltr, ifilter, LINE_MAX);
  1699. DPRINTF_S(fltr);
  1700. /* Save current */
  1701. if (ndents > 0)
  1702. mkpath(path, dents[cur].name, oldpath,
  1703. PATH_MAX);
  1704. goto nochange;
  1705. case SEL_MFLTR:
  1706. cfg.filtermode ^= 1;
  1707. if (cfg.filtermode)
  1708. presel = FILTER;
  1709. else
  1710. printmsg("navigate-as-you-type off");
  1711. goto nochange;
  1712. case SEL_SEARCH:
  1713. spawn(player, path, "search", NULL, F_NORMAL);
  1714. break;
  1715. case SEL_NEXT:
  1716. if (cur < ndents - 1)
  1717. ++cur;
  1718. else if (ndents)
  1719. /* Roll over, set cursor to first entry */
  1720. cur = 0;
  1721. break;
  1722. case SEL_PREV:
  1723. if (cur > 0)
  1724. --cur;
  1725. else if (ndents)
  1726. /* Roll over, set cursor to last entry */
  1727. cur = ndents - 1;
  1728. break;
  1729. case SEL_PGDN:
  1730. if (cur < ndents - 1)
  1731. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1732. break;
  1733. case SEL_PGUP:
  1734. if (cur > 0)
  1735. cur -= MIN((LINES - 4) / 2, cur);
  1736. break;
  1737. case SEL_HOME:
  1738. cur = 0;
  1739. break;
  1740. case SEL_END:
  1741. cur = ndents - 1;
  1742. break;
  1743. case SEL_CD:
  1744. {
  1745. static char *input;
  1746. static int truecd;
  1747. /* Save the program start dir */
  1748. tmp = getcwd(newpath, PATH_MAX);
  1749. if (tmp == NULL) {
  1750. printwarn();
  1751. goto nochange;
  1752. }
  1753. /* Switch to current path for readline(3) */
  1754. if (chdir(path) == -1) {
  1755. printwarn();
  1756. goto nochange;
  1757. }
  1758. endwin();
  1759. tmp = readline("chdir: ");
  1760. initcurses();
  1761. /* Change back to program start dir */
  1762. if (chdir(newpath) == -1)
  1763. printwarn();
  1764. if (tmp[0] == '\0')
  1765. break;
  1766. /* Add to readline(3) history */
  1767. add_history(tmp);
  1768. input = tmp;
  1769. tmp = strstrip(tmp);
  1770. if (tmp[0] == '\0') {
  1771. free(input);
  1772. break;
  1773. }
  1774. truecd = 0;
  1775. if (tmp[0] == '~') {
  1776. /* Expand ~ to HOME absolute path */
  1777. char *home = getenv("HOME");
  1778. if (home)
  1779. snprintf(newpath, PATH_MAX, "%s%s",
  1780. home, tmp + 1);
  1781. else {
  1782. free(input);
  1783. printmsg(STR_NOHOME);
  1784. goto nochange;
  1785. }
  1786. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1787. if (lastdir[0] == '\0') {
  1788. free(input);
  1789. break;
  1790. }
  1791. /* Switch to last visited dir */
  1792. xstrlcpy(newpath, lastdir, PATH_MAX);
  1793. truecd = 1;
  1794. } else if ((r = all_dots(tmp))) {
  1795. if (r == 1) {
  1796. /* Always in the current dir */
  1797. free(input);
  1798. break;
  1799. }
  1800. /* Show a message if already at / */
  1801. if (path[0] == '/' && path[1] == '\0') {
  1802. printmsg(STR_ATROOT);
  1803. free(input);
  1804. goto nochange;
  1805. }
  1806. --r; /* One . for the current dir */
  1807. dir = path;
  1808. /* Note: fd is used as a tmp variable here */
  1809. for (fd = 0; fd < r; ++fd) {
  1810. /* Reached / ? */
  1811. if (path[0] == '/' && path[1] == '\0') {
  1812. /* Can't cd beyond / */
  1813. break;
  1814. }
  1815. dir = xdirname(dir);
  1816. if (access(dir, R_OK) == -1) {
  1817. printwarn();
  1818. free(input);
  1819. goto nochange;
  1820. }
  1821. }
  1822. truecd = 1;
  1823. /* Save the path in case of cd ..
  1824. * We mark the current dir in parent dir
  1825. */
  1826. if (r == 1) {
  1827. xstrlcpy(oldpath, path, PATH_MAX);
  1828. truecd = 2;
  1829. }
  1830. xstrlcpy(newpath, dir, PATH_MAX);
  1831. } else
  1832. mkpath(path, tmp, newpath, PATH_MAX);
  1833. free(input);
  1834. if (access(newpath, R_OK) == -1) {
  1835. printwarn();
  1836. break;
  1837. }
  1838. if (truecd == 0) {
  1839. /* Probable change in dir */
  1840. /* No-op if it's the same directory */
  1841. if (xstrcmp(path, newpath) == 0)
  1842. break;
  1843. oldpath[0] = '\0';
  1844. } else if (truecd == 1)
  1845. /* Sure change in dir */
  1846. oldpath[0] = '\0';
  1847. /* Save last working directory */
  1848. xstrlcpy(lastdir, path, PATH_MAX);
  1849. /* Save the newly opted dir in path */
  1850. xstrlcpy(path, newpath, PATH_MAX);
  1851. /* Reset filter */
  1852. xstrlcpy(fltr, ifilter, LINE_MAX);
  1853. DPRINTF_S(path);
  1854. if (cfg.filtermode)
  1855. presel = FILTER;
  1856. goto begin;
  1857. }
  1858. case SEL_CDHOME:
  1859. tgt = getenv("HOME");
  1860. if (tgt == NULL) {
  1861. clearprompt();
  1862. goto nochange;
  1863. } // fallthrough
  1864. case SEL_CDBEGIN:
  1865. if (!tgt)
  1866. tgt = ipath;
  1867. if (access(tgt, R_OK) == -1) {
  1868. printwarn();
  1869. tgt = NULL;
  1870. goto nochange;
  1871. }
  1872. if (xstrcmp(path, tgt) == 0) {
  1873. tgt = NULL;
  1874. break;
  1875. }
  1876. /* Save last working directory */
  1877. xstrlcpy(lastdir, path, PATH_MAX);
  1878. xstrlcpy(path, tgt, PATH_MAX);
  1879. oldpath[0] = '\0';
  1880. /* Reset filter */
  1881. xstrlcpy(fltr, ifilter, LINE_MAX);
  1882. DPRINTF_S(path);
  1883. if (cfg.filtermode)
  1884. presel = FILTER;
  1885. tgt = NULL;
  1886. goto begin;
  1887. case SEL_CDLAST:
  1888. if (lastdir[0] == '\0') {
  1889. printmsg("Hit end of history...");
  1890. goto nochange;
  1891. }
  1892. if (access(lastdir, R_OK) == -1) {
  1893. printwarn();
  1894. goto nochange;
  1895. }
  1896. xstrlcpy(newpath, lastdir, PATH_MAX);
  1897. xstrlcpy(lastdir, path, PATH_MAX);
  1898. xstrlcpy(path, newpath, PATH_MAX);
  1899. oldpath[0] = '\0';
  1900. /* Reset filter */
  1901. xstrlcpy(fltr, ifilter, LINE_MAX);
  1902. DPRINTF_S(path);
  1903. if (cfg.filtermode)
  1904. presel = FILTER;
  1905. goto begin;
  1906. case SEL_CDBM:
  1907. printprompt("key: ");
  1908. tmp = readinput();
  1909. clearprompt();
  1910. if (tmp == NULL)
  1911. goto nochange;
  1912. for (r = 0; bookmark[r].key && r < MAX_BM; ++r) {
  1913. if (xstrcmp(bookmark[r].key, tmp) == -1)
  1914. continue;
  1915. if (bookmark[r].loc[0] == '~') {
  1916. /* Expand ~ to HOME */
  1917. char *home = getenv("HOME");
  1918. if (home)
  1919. snprintf(newpath,
  1920. PATH_MAX,
  1921. "%s%s",
  1922. home,
  1923. bookmark[r].loc
  1924. + 1);
  1925. else {
  1926. printmsg(STR_NOHOME);
  1927. goto nochange;
  1928. }
  1929. } else
  1930. mkpath(path, bookmark[r].loc,
  1931. newpath, PATH_MAX);
  1932. if (access(newpath, R_OK) == -1) {
  1933. printwarn();
  1934. goto nochange;
  1935. }
  1936. if (xstrcmp(path, newpath) == 0)
  1937. break;
  1938. oldpath[0] = '\0';
  1939. break;
  1940. }
  1941. if (!bookmark[r].key) {
  1942. printmsg("No matching bookmark");
  1943. goto nochange;
  1944. }
  1945. /* Save last working directory */
  1946. xstrlcpy(lastdir, path, PATH_MAX);
  1947. /* Save the newly opted dir in path */
  1948. xstrlcpy(path, newpath, PATH_MAX);
  1949. /* Reset filter */
  1950. xstrlcpy(fltr, ifilter, LINE_MAX);
  1951. DPRINTF_S(path);
  1952. if (cfg.filtermode)
  1953. presel = FILTER;
  1954. goto begin;
  1955. case SEL_TOGGLEDOT:
  1956. cfg.showhidden ^= 1;
  1957. initfilter(cfg.showhidden, &ifilter);
  1958. xstrlcpy(fltr, ifilter, LINE_MAX);
  1959. goto begin;
  1960. case SEL_DETAIL:
  1961. cfg.showdetail ^= 1;
  1962. cfg.showdetail ? (printptr = &printent_long)
  1963. : (printptr = &printent);
  1964. /* Save current */
  1965. if (ndents > 0)
  1966. mkpath(path, dents[cur].name, oldpath,
  1967. PATH_MAX);
  1968. goto begin;
  1969. case SEL_STATS:
  1970. {
  1971. struct stat sb;
  1972. if (ndents > 0) {
  1973. mkpath(path, dents[cur].name, oldpath,
  1974. PATH_MAX);
  1975. r = lstat(oldpath, &sb);
  1976. if (r == -1) {
  1977. if (dents)
  1978. dentfree(dents);
  1979. printerr(1, "lstat");
  1980. } else {
  1981. r = show_stats(oldpath, dents[cur].name,
  1982. &sb);
  1983. if (r < 0) {
  1984. printmsg(strerror(errno));
  1985. goto nochange;
  1986. }
  1987. }
  1988. }
  1989. break;
  1990. }
  1991. case SEL_MEDIA: // fallthrough
  1992. case SEL_FMEDIA:
  1993. if (ndents > 0) {
  1994. mkpath(path, dents[cur].name, oldpath,
  1995. PATH_MAX);
  1996. if (show_mediainfo(oldpath, run) == -1) {
  1997. sprintf(g_buf, "%s missing", metaviewer);
  1998. printmsg(g_buf);
  1999. goto nochange;
  2000. }
  2001. }
  2002. break;
  2003. case SEL_DFB:
  2004. if (!desktop_manager) {
  2005. printmsg("NNN_DE_FILE_MANAGER not set");
  2006. goto nochange;
  2007. }
  2008. spawn(desktop_manager, path, NULL, path,
  2009. F_NOTRACE | F_NOWAIT);
  2010. break;
  2011. case SEL_FSIZE:
  2012. cfg.sizeorder ^= 1;
  2013. cfg.mtimeorder = 0;
  2014. cfg.blkorder = 0;
  2015. /* Save current */
  2016. if (ndents > 0)
  2017. mkpath(path, dents[cur].name, oldpath,
  2018. PATH_MAX);
  2019. goto begin;
  2020. case SEL_BSIZE:
  2021. cfg.blkorder ^= 1;
  2022. if (cfg.blkorder) {
  2023. cfg.showdetail = 1;
  2024. printptr = &printent_long;
  2025. }
  2026. cfg.mtimeorder = 0;
  2027. cfg.sizeorder = 0;
  2028. /* Save current */
  2029. if (ndents > 0)
  2030. mkpath(path, dents[cur].name, oldpath,
  2031. PATH_MAX);
  2032. goto begin;
  2033. case SEL_MTIME:
  2034. cfg.mtimeorder ^= 1;
  2035. cfg.sizeorder = 0;
  2036. cfg.blkorder = 0;
  2037. /* Save current */
  2038. if (ndents > 0)
  2039. mkpath(path, dents[cur].name, oldpath,
  2040. PATH_MAX);
  2041. goto begin;
  2042. case SEL_REDRAW:
  2043. /* Save current */
  2044. if (ndents > 0)
  2045. mkpath(path, dents[cur].name, oldpath,
  2046. PATH_MAX);
  2047. goto begin;
  2048. case SEL_COPY:
  2049. if (copier && ndents) {
  2050. if (path[0] == '/' && path[1] == '\0')
  2051. snprintf(newpath, PATH_MAX, "/%s",
  2052. dents[cur].name);
  2053. else
  2054. snprintf(newpath, PATH_MAX, "%s/%s",
  2055. path, dents[cur].name);
  2056. spawn(copier, newpath, NULL, NULL, F_NONE);
  2057. printmsg(newpath);
  2058. } else if (!copier)
  2059. printmsg("NNN_COPIER is not set");
  2060. goto nochange;
  2061. case SEL_HELP:
  2062. show_help();
  2063. break;
  2064. case SEL_RUN:
  2065. run = xgetenv(env, run);
  2066. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2067. /* Repopulate as directory content may have changed */
  2068. goto begin;
  2069. case SEL_RUNARG:
  2070. run = xgetenv(env, run);
  2071. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2072. break;
  2073. }
  2074. /* Screensaver */
  2075. if (idletimeout != 0 && idle == idletimeout) {
  2076. idle = 0;
  2077. spawn(player, "", "screensaver", NULL,
  2078. F_NORMAL | F_SIGINT);
  2079. }
  2080. }
  2081. }
  2082. static void
  2083. usage(void)
  2084. {
  2085. printf("usage: nnn [-c N] [-e] [-i] [-l] [n]\n\
  2086. [-p nlay] [-S] [-v] [-h] [PATH]\n\n\
  2087. The missing terminal file browser for X.\n\n\
  2088. positional arguments:\n\
  2089. PATH directory to open [default: current dir]\n\n\
  2090. optional arguments:\n\
  2091. -c N specify dir color, disables if N>7\n\
  2092. -e use exiftool instead of mediainfo\n\
  2093. -i start in navigate-as-you-type mode\n\
  2094. -l start in light mode (fewer details)\n\
  2095. -n disable color for directory entries\n\
  2096. -p nlay path to custom nlay\n\
  2097. -S start in disk usage analyzer mode\n\
  2098. -v show program version and exit\n\
  2099. -h show this help and exit\n\n\
  2100. Version: %s\n\
  2101. License: BSD 2-Clause\n\
  2102. Webpage: https://github.com/jarun/nnn\n", VERSION);
  2103. exit(0);
  2104. }
  2105. int
  2106. main(int argc, char *argv[])
  2107. {
  2108. char cwd[PATH_MAX], *ipath;
  2109. char *ifilter, *bmstr;
  2110. int opt;
  2111. /* Confirm we are in a terminal */
  2112. if (!isatty(0) || !isatty(1)) {
  2113. fprintf(stderr, "stdin or stdout is not a tty\n");
  2114. exit(1);
  2115. }
  2116. while ((opt = getopt(argc, argv, "Slic:ep:vh")) != -1) {
  2117. switch (opt) {
  2118. case 'S':
  2119. cfg.blkorder = 1;
  2120. break;
  2121. case 'l':
  2122. cfg.showdetail = 0;
  2123. printptr = &printent;
  2124. break;
  2125. case 'i':
  2126. cfg.filtermode = 1;
  2127. break;
  2128. case 'c':
  2129. color = (uchar)atoi(optarg);
  2130. if (color > 7)
  2131. cfg.showcolor = 0;
  2132. break;
  2133. case 'e':
  2134. metaviewer = utils[3];
  2135. break;
  2136. case 'p':
  2137. player = optarg;
  2138. break;
  2139. case 'v':
  2140. printf("%s\n", VERSION);
  2141. return 0;
  2142. case 'h': // fallthrough
  2143. default:
  2144. usage();
  2145. }
  2146. }
  2147. if (argc == optind) {
  2148. /* Start in the current directory */
  2149. ipath = getcwd(cwd, PATH_MAX);
  2150. if (ipath == NULL)
  2151. ipath = "/";
  2152. } else {
  2153. ipath = realpath(argv[optind], cwd);
  2154. if (!ipath) {
  2155. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2156. exit(1);
  2157. }
  2158. }
  2159. /* Increase current open file descriptor limit */
  2160. open_max = max_openfds();
  2161. if (getuid() == 0)
  2162. cfg.showhidden = 1;
  2163. initfilter(cfg.showhidden, &ifilter);
  2164. /* Parse bookmarks string, if available */
  2165. bmstr = getenv("NNN_BMS");
  2166. if (bmstr)
  2167. parsebmstr(bmstr);
  2168. /* Edit text in EDITOR, if opted */
  2169. if (getenv("NNN_USE_EDITOR"))
  2170. editor = xgetenv("EDITOR", "vi");
  2171. /* Set metadata viewer if not set */
  2172. if (!metaviewer)
  2173. metaviewer = utils[2];
  2174. /* Set player if not set already */
  2175. if (!player)
  2176. player = utils[1];
  2177. /* Get the desktop file browser, if set */
  2178. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2179. /* Get screensaver wait time, if set; copier used as tmp var */
  2180. copier = getenv("NNN_IDLE_TIMEOUT");
  2181. if (copier)
  2182. idletimeout = abs(atoi(copier));
  2183. /* Get the default copier, if set */
  2184. copier = getenv("NNN_COPIER");
  2185. signal(SIGINT, SIG_IGN);
  2186. /* Test initial path */
  2187. if (access(ipath, R_OK) == -1) {
  2188. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2189. exit(1);
  2190. }
  2191. /* Set locale */
  2192. setlocale(LC_ALL, "");
  2193. #ifdef DEBUGMODE
  2194. enabledbg();
  2195. #endif
  2196. initcurses();
  2197. browse(ipath, ifilter);
  2198. endwin();
  2199. #ifdef DEBUGMODE
  2200. disabledbg();
  2201. #endif
  2202. exit(0);
  2203. }