My build of nnn with minor changes
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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