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