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.

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