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

nnn.c 74 KiB

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