My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

nnn.c 58 KiB

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