My build of nnn with minor changes
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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