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

nnn.c 61 KiB

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