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

nnn.c 71 KiB

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