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.

9 jaren geleden
9 jaren geleden
10 jaren geleden
9 jaren geleden
9 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
8 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
8 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
8 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
8 jaren geleden
7 jaren geleden
8 jaren geleden
8 jaren geleden
10 jaren geleden
10 jaren geleden
10 jaren geleden
10 jaren geleden
8 jaren geleden
8 jaren geleden
8 jaren geleden
10 jaren geleden
8 jaren geleden
8 jaren geleden
8 jaren geleden
8 jaren geleden
8 jaren geleden
8 jaren geleden
9 jaren geleden
8 jaren geleden
7 jaren geleden
7 jaren geleden
8 jaren geleden
8 jaren geleden
8 jaren geleden
8 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
8 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
8 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
8 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
8 jaren geleden
8 jaren geleden
7 jaren geleden
8 jaren geleden
7 jaren geleden
8 jaren geleden
8 jaren geleden
8 jaren geleden
8 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
8 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
10 jaren geleden
10 jaren geleden
10 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
10 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
8 jaren geleden
9 jaren geleden
7 jaren geleden
7 jaren geleden
9 jaren geleden
7 jaren geleden
9 jaren geleden
7 jaren geleden
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588
  1. /* See LICENSE file for copyright and license details. */
  2. #include <sys/stat.h>
  3. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  4. || defined(__APPLE__)
  5. # include <sys/types.h>
  6. #else
  7. # include <sys/sysmacros.h>
  8. #endif
  9. #include <sys/wait.h>
  10. #include <sys/statvfs.h>
  11. #include <sys/resource.h>
  12. #include <ctype.h>
  13. #include <curses.h>
  14. #include <dirent.h>
  15. #include <errno.h>
  16. #include <fcntl.h>
  17. #include <grp.h>
  18. #include <libgen.h>
  19. #include <limits.h>
  20. #ifdef __gnu_hurd__
  21. #define PATH_MAX 4096
  22. #endif
  23. #include <locale.h>
  24. #include <pwd.h>
  25. #include <regex.h>
  26. #include <signal.h>
  27. #include <stdarg.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <time.h>
  32. #include <unistd.h>
  33. #include <wchar.h>
  34. #include <readline/readline.h>
  35. #ifndef __USE_XOPEN_EXTENDED
  36. #define __USE_XOPEN_EXTENDED 1
  37. #endif
  38. #include <ftw.h>
  39. #include "config.h"
  40. #ifdef DEBUGMODE
  41. static int DEBUG_FD;
  42. static int
  43. xprintf(int fd, const char *fmt, ...)
  44. {
  45. char buf[BUFSIZ];
  46. int r;
  47. va_list ap;
  48. va_start(ap, fmt);
  49. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  50. if (r > 0)
  51. r = write(fd, buf, r);
  52. va_end(ap);
  53. return r;
  54. }
  55. static int
  56. enabledbg()
  57. {
  58. FILE *fp = fopen("/tmp/nnn_debug", "w");
  59. if (!fp) {
  60. fprintf(stderr, "Cannot open debug file\n");
  61. return -1;
  62. }
  63. DEBUG_FD = fileno(fp);
  64. if (DEBUG_FD == -1) {
  65. fprintf(stderr, "Cannot open debug file descriptor\n");
  66. return -1;
  67. }
  68. return 0;
  69. }
  70. static void
  71. disabledbg()
  72. {
  73. close(DEBUG_FD);
  74. }
  75. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  76. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  77. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  78. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=0x%p\n", x)
  79. #else
  80. #define DPRINTF_D(x)
  81. #define DPRINTF_U(x)
  82. #define DPRINTF_S(x)
  83. #define DPRINTF_P(x)
  84. #endif /* DEBUGMODE */
  85. /* Macro definitions */
  86. #define VERSION "1.2"
  87. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  88. #undef MIN
  89. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  90. #define ISODD(x) ((x) & 1)
  91. #define TOUPPER(ch) \
  92. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  93. #define MAX_CMD_LEN 5120
  94. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  95. #define FILTER '/'
  96. #define MAX_BM 10
  97. /* Macros to define process spawn behaviour as flags */
  98. #define F_NONE 0x00 /* no flag set */
  99. #define F_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
  100. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  101. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  102. #define F_SIGINT 0x08 /* restore default SIGINT handler */
  103. #define F_NORMAL 0x80 /* spawn child process in non-curses regular mode */
  104. typedef unsigned long ulong;
  105. typedef unsigned int uint;
  106. typedef unsigned char uchar;
  107. /* Directory entry */
  108. typedef struct entry {
  109. char name[NAME_MAX];
  110. mode_t mode;
  111. time_t t;
  112. off_t size;
  113. blkcnt_t blocks; /* number of 512B blocks allocated */
  114. } *pEntry;
  115. /* Bookmark */
  116. typedef struct {
  117. char *key;
  118. char *loc;
  119. } bm;
  120. /* Settings */
  121. typedef struct {
  122. uchar filtermode : 1; /* Set to enter filter mode */
  123. uchar mtimeorder : 1; /* Set to sort by time modified */
  124. uchar sizeorder : 1; /* Set to sort by file size */
  125. uchar blkorder : 1; /* Set to sort by blocks used (disk usage) */
  126. uchar showhidden : 1; /* Set to show hidden files */
  127. uchar showdetail : 1; /* Clear to show fewer file info */
  128. uchar showcolor : 1; /* Set to show dirs in blue */
  129. uchar dircolor : 1; /* Current status of dir color */
  130. } settings;
  131. /* Externs */
  132. #ifdef __APPLE__
  133. extern int add_history(const char *string);
  134. #else
  135. extern void add_history(const char *string);
  136. #endif
  137. extern int wget_wch(WINDOW *win, wint_t *wch);
  138. /* Globals */
  139. /* Configuration */
  140. static settings cfg = {0, 0, 0, 0, 0, 1, 1, 0};
  141. /* Idle timeout in seconds, 0 to disable */
  142. static uint idletimeout;
  143. static struct entry *dents;
  144. static int ndents, cur, total_dents;
  145. static uint idle;
  146. static char *player;
  147. static char *copier;
  148. static char *editor;
  149. static char *desktop_manager;
  150. static blkcnt_t ent_blocks;
  151. static blkcnt_t dir_blocks;
  152. static ulong num_files;
  153. static size_t fs_free;
  154. static uint open_max;
  155. static bm bookmark[MAX_BM];
  156. static const double div_2_pow_10 = 1.0 / 1024.0;
  157. static uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
  158. static uchar color = 4;
  159. /* Utilities to open files, run actions */
  160. static char * const utils[] = {
  161. #ifdef __APPLE__
  162. "/usr/bin/open",
  163. #else
  164. "/usr/bin/xdg-open",
  165. #endif
  166. "nlay",
  167. "mediainfo",
  168. "exiftool"
  169. };
  170. static char *metaviewer;
  171. /* For use in functions which are isolated and don't return the buffer */
  172. static char g_buf[MAX_CMD_LEN];
  173. /*
  174. * Layout:
  175. * .---------
  176. * | cwd: /mnt/path
  177. * |
  178. * | file0
  179. * | file1
  180. * | > file2
  181. * | file3
  182. * | file4
  183. * ...
  184. * | filen
  185. * |
  186. * | Permission denied
  187. * '------
  188. */
  189. /* Forward declarations */
  190. static void printmsg(char *);
  191. static void printwarn(void);
  192. static void printerr(int, char *);
  193. static void redraw(char *path);
  194. /* Functions */
  195. /* Increase the limit on open file descriptors, if possible */
  196. static rlim_t
  197. max_openfds()
  198. {
  199. struct rlimit rl;
  200. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  201. if (limit != 0)
  202. return 32;
  203. limit = rl.rlim_cur;
  204. rl.rlim_cur = rl.rlim_max;
  205. if (setrlimit(RLIMIT_NOFILE, &rl) == 0)
  206. return rl.rlim_max - 64;
  207. if (limit > 128)
  208. return limit - 64;
  209. return 32;
  210. }
  211. /*
  212. * Custom xstrlen()
  213. */
  214. static size_t
  215. xstrlen(const char *s)
  216. {
  217. static size_t len;
  218. if (!s)
  219. return 0;
  220. len = 0;
  221. while (*s)
  222. ++len, ++s;
  223. return len;
  224. }
  225. /*
  226. * Just a safe strncpy(3)
  227. * Always null ('\0') terminates if both src and dest are valid pointers.
  228. * Returns the number of bytes copied including terminating null byte.
  229. */
  230. static size_t
  231. xstrlcpy(char *dest, const char *src, size_t n)
  232. {
  233. static size_t len, blocks;
  234. if (!src || !dest)
  235. return 0;
  236. len = xstrlen(src) + 1;
  237. if (n > len)
  238. n = len;
  239. else if (len > n)
  240. /* Save total number of bytes to copy in len */
  241. len = n;
  242. blocks = n >> _WSHIFT;
  243. n -= (blocks << _WSHIFT);
  244. if (blocks) {
  245. static ulong *s, *d;
  246. s = (ulong *)src;
  247. d = (ulong *)dest;
  248. while (blocks) {
  249. *d = *s;
  250. ++d, ++s;
  251. --blocks;
  252. }
  253. if (!n) {
  254. dest = (char *)d;
  255. *--dest = '\0';
  256. return len;
  257. }
  258. src = (char *)s;
  259. dest = (char *)d;
  260. }
  261. while (--n && (*dest = *src))
  262. ++dest, ++src;
  263. if (!n)
  264. *dest = '\0';
  265. return len;
  266. }
  267. /*
  268. * Custom strcmp(), just what we need.
  269. * Returns 0 if same, else -1
  270. */
  271. static int
  272. xstrcmp(const char *s1, const char *s2)
  273. {
  274. if (!s1 || !s2)
  275. return -1;
  276. while (*s1 && *s1 == *s2)
  277. ++s1, ++s2;
  278. if (*s1 != *s2)
  279. return -1;
  280. return 0;
  281. }
  282. /*
  283. * The poor man's implementation of memrchr(3).
  284. * We are only looking for '/' in this program.
  285. */
  286. static void *
  287. xmemrchr(const void *s, uchar ch, size_t n)
  288. {
  289. if (!s || !n)
  290. return NULL;
  291. static uchar *p;
  292. p = (uchar *)s + n - 1;
  293. while (n) {
  294. if (*p == ch)
  295. return p;
  296. --p;
  297. --n;
  298. }
  299. return NULL;
  300. }
  301. /*
  302. * The following dirname(3) implementation does not
  303. * modify the input. We use a copy of the original.
  304. *
  305. * Modified from the glibc (GNU LGPL) version.
  306. */
  307. static char *
  308. xdirname(const char *path)
  309. {
  310. static char buf[PATH_MAX];
  311. static char *last_slash;
  312. xstrlcpy(buf, path, PATH_MAX);
  313. /* Find last '/'. */
  314. last_slash = strrchr(buf, '/');
  315. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  316. /* Determine whether all remaining characters are slashes. */
  317. char *runp;
  318. for (runp = last_slash; runp != buf; --runp)
  319. if (runp[-1] != '/')
  320. break;
  321. /* The '/' is the last character, we have to look further. */
  322. if (runp != buf)
  323. last_slash = xmemrchr(buf, '/', runp - buf);
  324. }
  325. if (last_slash != NULL) {
  326. /* Determine whether all remaining characters are slashes. */
  327. char *runp;
  328. for (runp = last_slash; runp != buf; --runp)
  329. if (runp[-1] != '/')
  330. break;
  331. /* Terminate the buffer. */
  332. if (runp == buf) {
  333. /* The last slash is the first character in the string.
  334. * We have to return "/". As a special case we have to
  335. * return "//" if there are exactly two slashes at the
  336. * beginning of the string. See XBD 4.10 Path Name
  337. * Resolution for more information.
  338. */
  339. if (last_slash == buf + 1)
  340. ++last_slash;
  341. else
  342. last_slash = buf + 1;
  343. } else
  344. last_slash = runp;
  345. last_slash[0] = '\0';
  346. } else {
  347. /* This assignment is ill-designed but the XPG specs require to
  348. * return a string containing "." in any case no directory part
  349. * is found and so a static and constant string is required.
  350. */
  351. buf[0] = '.';
  352. buf[1] = '\0';
  353. }
  354. return buf;
  355. }
  356. /*
  357. * Return number of dots if all chars in a string are dots, else 0
  358. */
  359. static int
  360. all_dots(const char *ptr)
  361. {
  362. if (!ptr)
  363. return FALSE;
  364. int count = 0;
  365. while (*ptr == '.')
  366. ++count, ++ptr;
  367. if (*ptr)
  368. return 0;
  369. return count;
  370. }
  371. /* Initialize curses mode */
  372. static void
  373. initcurses(void)
  374. {
  375. if (initscr() == NULL) {
  376. char *term = getenv("TERM");
  377. if (term != NULL)
  378. fprintf(stderr, "error opening terminal: %s\n", term);
  379. else
  380. fprintf(stderr, "failed to initialize curses\n");
  381. exit(1);
  382. }
  383. cbreak();
  384. noecho();
  385. nonl();
  386. intrflush(stdscr, FALSE);
  387. keypad(stdscr, TRUE);
  388. curs_set(FALSE); /* Hide cursor */
  389. start_color();
  390. use_default_colors();
  391. if (cfg.showcolor)
  392. init_pair(1, color, -1);
  393. timeout(1000); /* One second */
  394. }
  395. /* Exit curses mode */
  396. static void
  397. exitcurses(void)
  398. {
  399. endwin(); /* Restore terminal */
  400. }
  401. /*
  402. * Spawns a child process. Behaviour can be controlled using flag.
  403. * Limited to 2 arguments to a program, flag works on bit set.
  404. */
  405. static void
  406. spawn(char *file, char *arg1, char *arg2, char *dir, uchar flag)
  407. {
  408. pid_t pid;
  409. int status;
  410. if (flag & F_NORMAL)
  411. exitcurses();
  412. pid = fork();
  413. if (pid == 0) {
  414. if (dir != NULL)
  415. status = chdir(dir);
  416. /* Show a marker (to indicate nnn spawned shell) */
  417. if (flag & F_MARKER) {
  418. printf("\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  419. printf("Spawned shell level: %d\n",
  420. atoi(getenv("SHLVL")) + 1);
  421. }
  422. /* Suppress stdout and stderr */
  423. if (flag & F_NOTRACE) {
  424. int fd = open("/dev/null", O_WRONLY, 0200);
  425. dup2(fd, 1);
  426. dup2(fd, 2);
  427. close(fd);
  428. }
  429. if (flag & F_SIGINT)
  430. signal(SIGINT, SIG_DFL);
  431. execlp(file, file, arg1, arg2, NULL);
  432. _exit(1);
  433. } else {
  434. if (!(flag & F_NOWAIT))
  435. /* Ignore interruptions */
  436. while (waitpid(pid, &status, 0) == -1)
  437. DPRINTF_D(status);
  438. DPRINTF_D(pid);
  439. if (flag & F_NORMAL)
  440. initcurses();
  441. }
  442. }
  443. /* Get program name from env var, else return fallback program */
  444. static char *
  445. xgetenv(char *name, char *fallback)
  446. {
  447. if (name == NULL)
  448. return fallback;
  449. char *value = getenv(name);
  450. return value && value[0] ? value : fallback;
  451. }
  452. /*
  453. * We assume none of the strings are NULL.
  454. *
  455. * Let's have the logic to sort numeric names in numeric order.
  456. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  457. *
  458. * If the absolute numeric values are same, we fallback to alphasort.
  459. */
  460. static int
  461. xstricmp(char *s1, char *s2)
  462. {
  463. static char *c1, *c2;
  464. c1 = s1;
  465. while (isspace(*c1))
  466. ++c1;
  467. if (*c1 == '-' || *c1 == '+')
  468. ++c1;
  469. while (*c1 >= '0' && *c1 <= '9')
  470. ++c1;
  471. c2 = s2;
  472. while (isspace(*c2))
  473. ++c2;
  474. if (*c2 == '-' || *c2 == '+')
  475. ++c2;
  476. while (*c2 >= '0' && *c2 <= '9')
  477. ++c2;
  478. if (*c1 == '\0' && *c2 == '\0') {
  479. static long long num1, num2;
  480. num1 = strtoll(s1, &c1, 10);
  481. num2 = strtoll(s2, &c2, 10);
  482. if (num1 != num2) {
  483. if (num1 > num2)
  484. return 1;
  485. else
  486. return -1;
  487. }
  488. } else if (*c1 == '\0' && *c2 != '\0')
  489. return -1;
  490. else if (*c1 != '\0' && *c2 == '\0')
  491. return 1;
  492. while (*s2 && *s1 && TOUPPER(*s1) == TOUPPER(*s2))
  493. ++s1, ++s2;
  494. /* In case of alphabetically same names, make sure
  495. * lower case one comes before upper case one
  496. */
  497. if (!*s1 && !*s2)
  498. return 1;
  499. return (int) (TOUPPER(*s1) - TOUPPER(*s2));
  500. }
  501. /* Trim all whitespace from both ends, / from end */
  502. static char *
  503. strstrip(char *s)
  504. {
  505. if (!s || !*s)
  506. return s;
  507. size_t len = xstrlen(s) - 1;
  508. while (len != 0 && (isspace(s[len]) || s[len] == '/'))
  509. --len;
  510. s[len + 1] = '\0';
  511. while (*s && isspace(*s))
  512. ++s;
  513. return s;
  514. }
  515. static char *
  516. getmime(char *file)
  517. {
  518. regex_t regex;
  519. uint i;
  520. static uint len = LEN(assocs);
  521. for (i = 0; i < len; ++i) {
  522. if (regcomp(&regex, assocs[i].regex,
  523. REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  524. continue;
  525. if (regexec(&regex, file, 0, NULL, 0) == 0)
  526. return assocs[i].mime;
  527. }
  528. return NULL;
  529. }
  530. static int
  531. setfilter(regex_t *regex, char *filter)
  532. {
  533. static size_t len;
  534. static int r;
  535. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  536. if (r != 0 && filter && filter[0] != '\0') {
  537. len = COLS;
  538. if (len > LINE_MAX)
  539. len = LINE_MAX;
  540. regerror(r, regex, g_buf, len);
  541. printmsg(g_buf);
  542. }
  543. return r;
  544. }
  545. static void
  546. initfilter(int dot, char **ifilter)
  547. {
  548. *ifilter = dot ? "." : "^[^.]";
  549. }
  550. static int
  551. visible(regex_t *regex, char *file)
  552. {
  553. return regexec(regex, file, 0, NULL, 0) == 0;
  554. }
  555. static int
  556. entrycmp(const void *va, const void *vb)
  557. {
  558. static pEntry pa, pb;
  559. pa = (pEntry)va;
  560. pb = (pEntry)vb;
  561. /* Sort directories first */
  562. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  563. return 1;
  564. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  565. return -1;
  566. /* Do the actual sorting */
  567. if (cfg.mtimeorder)
  568. return pb->t - pa->t;
  569. if (cfg.sizeorder) {
  570. if (pb->size > pa->size)
  571. return 1;
  572. else if (pb->size < pa->size)
  573. return -1;
  574. }
  575. if (cfg.blkorder) {
  576. if (pb->blocks > pa->blocks)
  577. return 1;
  578. else if (pb->blocks < pa->blocks)
  579. return -1;
  580. }
  581. return xstricmp(pa->name, pb->name);
  582. }
  583. /* Messages show up at the bottom */
  584. static void
  585. printmsg(char *msg)
  586. {
  587. mvprintw(LINES - 1, 0, "%s\n", msg);
  588. }
  589. /* Display warning as a message */
  590. static void
  591. printwarn(void)
  592. {
  593. printmsg(strerror(errno));
  594. }
  595. /* Kill curses and display error before exiting */
  596. static void
  597. printerr(int ret, char *prefix)
  598. {
  599. exitcurses();
  600. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  601. exit(ret);
  602. }
  603. /* Clear the last line */
  604. static void
  605. clearprompt(void)
  606. {
  607. printmsg("");
  608. }
  609. /* Print prompt on the last line */
  610. static void
  611. printprompt(char *str)
  612. {
  613. clearprompt();
  614. printw(str);
  615. }
  616. /* Returns SEL_* if key is bound and 0 otherwise.
  617. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  618. * The next keyboard input can be simulated by presel.
  619. */
  620. static int
  621. nextsel(char **run, char **env, int *presel)
  622. {
  623. static int c;
  624. static uchar i;
  625. static uint len = LEN(bindings);
  626. c = *presel;
  627. if (c == 0)
  628. c = getch();
  629. else
  630. *presel = 0;
  631. if (c == -1)
  632. ++idle;
  633. else
  634. idle = 0;
  635. for (i = 0; i < len; ++i)
  636. if (c == bindings[i].sym) {
  637. *run = bindings[i].run;
  638. *env = bindings[i].env;
  639. return bindings[i].act;
  640. }
  641. return 0;
  642. }
  643. /*
  644. * Move non-matching entries to the end
  645. */
  646. static void
  647. fill(struct entry **dents,
  648. int (*filter)(regex_t *, char *), regex_t *re)
  649. {
  650. static int count;
  651. for (count = 0; count < ndents; ++count) {
  652. if (filter(re, (*dents)[count].name) == 0) {
  653. if (count != --ndents) {
  654. static struct entry _dent;
  655. /* Copy count to tmp */
  656. xstrlcpy(_dent.name, (*dents)[count].name,
  657. NAME_MAX);
  658. _dent.mode = (*dents)[count].mode;
  659. _dent.t = (*dents)[count].t;
  660. _dent.size = (*dents)[count].size;
  661. _dent.blocks = (*dents)[count].blocks;
  662. /* Copy ndents - 1 to count */
  663. xstrlcpy((*dents)[count].name,
  664. (*dents)[ndents].name, NAME_MAX);
  665. (*dents)[count].mode = (*dents)[ndents].mode;
  666. (*dents)[count].t = (*dents)[ndents].t;
  667. (*dents)[count].size = (*dents)[ndents].size;
  668. (*dents)[count].blocks
  669. = (*dents)[ndents].blocks;
  670. /* Copy tmp to ndents - 1 */
  671. xstrlcpy((*dents)[ndents].name, _dent.name,
  672. NAME_MAX);
  673. (*dents)[ndents].mode = _dent.mode;
  674. (*dents)[ndents].t = _dent.t;
  675. (*dents)[ndents].size = _dent.size;
  676. (*dents)[ndents].blocks = _dent.blocks;
  677. --count;
  678. }
  679. continue;
  680. }
  681. }
  682. }
  683. static int
  684. matches(char *fltr)
  685. {
  686. static regex_t re;
  687. /* Search filter */
  688. if (setfilter(&re, fltr) != 0)
  689. return -1;
  690. fill(&dents, visible, &re);
  691. qsort(dents, ndents, sizeof(*dents), entrycmp);
  692. return 0;
  693. }
  694. static int
  695. readln(char *path)
  696. {
  697. static char ln[LINE_MAX << 2];
  698. static wchar_t wln[LINE_MAX];
  699. static wint_t ch[2] = {0};
  700. int r, total = ndents;
  701. int oldcur = cur;
  702. int len = 1;
  703. char *pln = ln + 1;
  704. memset(wln, 0, LINE_MAX << 2);
  705. wln[0] = FILTER;
  706. ln[0] = FILTER;
  707. ln[1] = '\0';
  708. cur = 0;
  709. timeout(-1);
  710. echo();
  711. curs_set(TRUE);
  712. printprompt(ln);
  713. while ((r = wget_wch(stdscr, ch)) != ERR)
  714. if (r == OK)
  715. switch (*ch) {
  716. case '\r': // with nonl(), this is ENTER key value
  717. if (len == 1) {
  718. cur = oldcur;
  719. goto end;
  720. }
  721. if (matches(pln) == -1)
  722. goto end;
  723. redraw(path);
  724. goto end;
  725. case 127: // handle DEL
  726. if (len == 1) {
  727. cur = oldcur;
  728. *ch = CONTROL('L');
  729. goto end;
  730. }
  731. wln[--len] = '\0';
  732. if (len == 1)
  733. cur = oldcur;
  734. wcstombs(ln, wln, LINE_MAX << 2);
  735. ndents = total;
  736. if (matches(pln) == -1) {
  737. printprompt(ln);
  738. continue;
  739. }
  740. redraw(path);
  741. printprompt(ln);
  742. break;
  743. case CONTROL('L'):
  744. if (len == 1)
  745. cur = oldcur; // fallthrough
  746. case CONTROL('Q'):
  747. goto end;
  748. default:
  749. /* Reset cur in case it's a repeat search */
  750. if (len == 1)
  751. cur = 0;
  752. wln[len] = (wchar_t)*ch;
  753. wln[++len] = '\0';
  754. wcstombs(ln, wln, LINE_MAX << 2);
  755. ndents = total;
  756. if (matches(pln) == -1)
  757. continue;
  758. redraw(path);
  759. printprompt(ln);
  760. }
  761. else
  762. switch (*ch) {
  763. case KEY_DC: // fallthrough
  764. case KEY_BACKSPACE:
  765. if (len == 1) {
  766. cur = oldcur;
  767. *ch = CONTROL('L');
  768. goto end;
  769. }
  770. wln[--len] = '\0';
  771. if (len == 1)
  772. cur = oldcur;
  773. wcstombs(ln, wln, LINE_MAX << 2);
  774. ndents = total;
  775. if (matches(pln) == -1)
  776. continue;
  777. redraw(path);
  778. printprompt(ln);
  779. break;
  780. case KEY_DOWN: // fallthrough
  781. case KEY_UP: // fallthrough
  782. case KEY_LEFT: // fallthrough
  783. case KEY_RIGHT: // fallthrough
  784. case KEY_F(2):
  785. if (len == 1)
  786. cur = oldcur; // fallthrough
  787. default:
  788. goto end;
  789. }
  790. end:
  791. noecho();
  792. curs_set(FALSE);
  793. timeout(1000);
  794. /* Return keys for navigation etc. */
  795. return *ch;
  796. }
  797. /*
  798. * Returns "dir/name or "/name"
  799. */
  800. static char *
  801. mkpath(char *dir, char *name, char *out, size_t n)
  802. {
  803. /* Handle absolute path */
  804. if (name[0] == '/')
  805. xstrlcpy(out, name, n);
  806. else {
  807. /* Handle root case */
  808. if (dir[0] == '/' && dir[1] == '\0')
  809. snprintf(out, n, "/%s", name);
  810. else
  811. snprintf(out, n, "%s/%s", dir, name);
  812. }
  813. return out;
  814. }
  815. static void
  816. parsebmstr(char *bms)
  817. {
  818. int i = 0;
  819. while (*bms && i < MAX_BM) {
  820. bookmark[i].key = bms;
  821. ++bms;
  822. while (*bms && *bms != ':')
  823. ++bms;
  824. if (!*bms) {
  825. bookmark[i].key = NULL;
  826. break;
  827. }
  828. *bms = '\0';
  829. bookmark[i].loc = ++bms;
  830. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  831. bookmark[i].key = NULL;
  832. break;
  833. }
  834. while (*bms && *bms != ';')
  835. ++bms;
  836. if (*bms)
  837. *bms = '\0';
  838. else
  839. break;
  840. ++bms;
  841. ++i;
  842. }
  843. }
  844. static char *
  845. readinput(void)
  846. {
  847. timeout(-1);
  848. echo();
  849. curs_set(TRUE);
  850. memset(g_buf, 0, LINE_MAX);
  851. wgetnstr(stdscr, g_buf, LINE_MAX - 1);
  852. noecho();
  853. curs_set(FALSE);
  854. timeout(1000);
  855. return g_buf[0] ? g_buf : NULL;
  856. }
  857. /*
  858. * Replace escape characters in a string with '?'
  859. */
  860. static char *
  861. unescape(const char *str)
  862. {
  863. static char buffer[PATH_MAX];
  864. static wchar_t wbuf[PATH_MAX];
  865. static wchar_t *buf;
  866. buffer[0] = '\0';
  867. buf = wbuf;
  868. /* Convert multi-byte to wide char */
  869. mbstowcs(wbuf, str, PATH_MAX);
  870. while (*buf) {
  871. if (*buf <= '\x1f' || *buf == '\x7f')
  872. *buf = '\?';
  873. ++buf;
  874. }
  875. /* Convert wide char to multi-byte */
  876. wcstombs(buffer, wbuf, PATH_MAX);
  877. return buffer;
  878. }
  879. static void
  880. printent(struct entry *ent, int sel)
  881. {
  882. static int ncols;
  883. if (PATH_MAX + 16 < COLS)
  884. ncols = PATH_MAX + 16;
  885. else
  886. ncols = COLS;
  887. if (S_ISDIR(ent->mode))
  888. snprintf(g_buf, ncols, "%s%s/", CURSYM(sel),
  889. unescape(ent->name));
  890. else if (S_ISLNK(ent->mode))
  891. snprintf(g_buf, ncols, "%s%s@", CURSYM(sel),
  892. unescape(ent->name));
  893. else if (S_ISSOCK(ent->mode))
  894. snprintf(g_buf, ncols, "%s%s=", CURSYM(sel),
  895. unescape(ent->name));
  896. else if (S_ISFIFO(ent->mode))
  897. snprintf(g_buf, ncols, "%s%s|", CURSYM(sel),
  898. unescape(ent->name));
  899. else if (ent->mode & 0100)
  900. snprintf(g_buf, ncols, "%s%s*", CURSYM(sel),
  901. unescape(ent->name));
  902. else
  903. snprintf(g_buf, ncols, "%s%s", CURSYM(sel),
  904. unescape(ent->name));
  905. /* Dirs are always shown on top */
  906. if (cfg.dircolor && !S_ISDIR(ent->mode)) {
  907. attroff(COLOR_PAIR(1) | A_BOLD);
  908. cfg.dircolor = 0;
  909. }
  910. printw("%s\n", g_buf);
  911. }
  912. static char *
  913. coolsize(off_t size)
  914. {
  915. static const char * const U[]
  916. = {"B", "K", "M", "G", "T", "P", "E", "Z", "Y"};
  917. static char size_buf[12]; /* Buffer to hold human readable size */
  918. static int i;
  919. static off_t tmp;
  920. static long double rem;
  921. i = 0;
  922. rem = 0;
  923. while (size > 1024) {
  924. tmp = size;
  925. size >>= 10;
  926. rem = tmp - (size << 10);
  927. ++i;
  928. }
  929. snprintf(size_buf, 12, "%.*Lf%s", i, size + rem * div_2_pow_10, U[i]);
  930. return size_buf;
  931. }
  932. static void
  933. printent_long(struct entry *ent, int sel)
  934. {
  935. static int ncols;
  936. static char buf[18];
  937. if (PATH_MAX + 32 < COLS)
  938. ncols = PATH_MAX + 32;
  939. else
  940. ncols = COLS;
  941. strftime(buf, 18, "%d %m %Y %H:%M", localtime(&ent->t));
  942. if (sel)
  943. attron(A_REVERSE);
  944. if (!cfg.blkorder) {
  945. if (S_ISDIR(ent->mode))
  946. snprintf(g_buf, ncols, "%s%-16.16s / %s/",
  947. CURSYM(sel), buf, unescape(ent->name));
  948. else if (S_ISLNK(ent->mode))
  949. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  950. CURSYM(sel), buf, unescape(ent->name));
  951. else if (S_ISSOCK(ent->mode))
  952. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  953. CURSYM(sel), buf, unescape(ent->name));
  954. else if (S_ISFIFO(ent->mode))
  955. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  956. CURSYM(sel), buf, unescape(ent->name));
  957. else if (S_ISBLK(ent->mode))
  958. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  959. CURSYM(sel), buf, unescape(ent->name));
  960. else if (S_ISCHR(ent->mode))
  961. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  962. CURSYM(sel), buf, unescape(ent->name));
  963. else if (ent->mode & 0100)
  964. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  965. CURSYM(sel), buf, coolsize(ent->size),
  966. unescape(ent->name));
  967. else
  968. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  969. CURSYM(sel), buf, coolsize(ent->size),
  970. unescape(ent->name));
  971. } else {
  972. if (S_ISDIR(ent->mode))
  973. snprintf(g_buf, ncols, "%s%-16.16s %8.8s/ %s/",
  974. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  975. unescape(ent->name));
  976. else if (S_ISLNK(ent->mode))
  977. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  978. CURSYM(sel), buf,
  979. unescape(ent->name));
  980. else if (S_ISSOCK(ent->mode))
  981. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  982. CURSYM(sel), buf,
  983. unescape(ent->name));
  984. else if (S_ISFIFO(ent->mode))
  985. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  986. CURSYM(sel), buf,
  987. unescape(ent->name));
  988. else if (S_ISBLK(ent->mode))
  989. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  990. CURSYM(sel), buf,
  991. unescape(ent->name));
  992. else if (S_ISCHR(ent->mode))
  993. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  994. CURSYM(sel), buf,
  995. unescape(ent->name));
  996. else if (ent->mode & 0100)
  997. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  998. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  999. unescape(ent->name));
  1000. else
  1001. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  1002. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  1003. unescape(ent->name));
  1004. }
  1005. /* Dirs are always shown on top */
  1006. if (cfg.dircolor && !S_ISDIR(ent->mode)) {
  1007. attroff(COLOR_PAIR(1) | A_BOLD);
  1008. cfg.dircolor = 0;
  1009. }
  1010. printw("%s\n", g_buf);
  1011. if (sel)
  1012. attroff(A_REVERSE);
  1013. }
  1014. static void (*printptr)(struct entry *ent, int sel) = &printent_long;
  1015. static char
  1016. get_fileind(mode_t mode, char *desc)
  1017. {
  1018. static char c;
  1019. if (S_ISREG(mode)) {
  1020. c = '-';
  1021. sprintf(desc, "%s", "regular file");
  1022. if (mode & 0100)
  1023. strcat(desc, ", executable");
  1024. } else if (S_ISDIR(mode)) {
  1025. c = 'd';
  1026. sprintf(desc, "%s", "directory");
  1027. } else if (S_ISBLK(mode)) {
  1028. c = 'b';
  1029. sprintf(desc, "%s", "block special device");
  1030. } else if (S_ISCHR(mode)) {
  1031. c = 'c';
  1032. sprintf(desc, "%s", "character special device");
  1033. #ifdef S_ISFIFO
  1034. } else if (S_ISFIFO(mode)) {
  1035. c = 'p';
  1036. sprintf(desc, "%s", "FIFO");
  1037. #endif /* S_ISFIFO */
  1038. #ifdef S_ISLNK
  1039. } else if (S_ISLNK(mode)) {
  1040. c = 'l';
  1041. sprintf(desc, "%s", "symbolic link");
  1042. #endif /* S_ISLNK */
  1043. #ifdef S_ISSOCK
  1044. } else if (S_ISSOCK(mode)) {
  1045. c = 's';
  1046. sprintf(desc, "%s", "socket");
  1047. #endif /* S_ISSOCK */
  1048. #ifdef S_ISDOOR
  1049. /* Solaris 2.6, etc. */
  1050. } else if (S_ISDOOR(mode)) {
  1051. c = 'D';
  1052. desc[0] = '\0';
  1053. #endif /* S_ISDOOR */
  1054. } else {
  1055. /* Unknown type -- possibly a regular file? */
  1056. c = '?';
  1057. desc[0] = '\0';
  1058. }
  1059. return c;
  1060. }
  1061. /* Convert a mode field into "ls -l" type perms field. */
  1062. static char *
  1063. get_lsperms(mode_t mode, char *desc)
  1064. {
  1065. static const char * const rwx[] = {"---", "--x", "-w-", "-wx",
  1066. "r--", "r-x", "rw-", "rwx"};
  1067. static char bits[11];
  1068. bits[0] = get_fileind(mode, desc);
  1069. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  1070. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  1071. strcpy(&bits[7], rwx[(mode & 7)]);
  1072. if (mode & S_ISUID)
  1073. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1074. if (mode & S_ISGID)
  1075. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1076. if (mode & S_ISVTX)
  1077. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1078. bits[10] = '\0';
  1079. return bits;
  1080. }
  1081. /*
  1082. * Gets only a single line (that's what we need
  1083. * for now) or shows full command output in pager.
  1084. *
  1085. * If pager is valid, returns NULL
  1086. */
  1087. static char *
  1088. get_output(char *buf, size_t bytes, char *file,
  1089. char *arg1, char *arg2, int pager)
  1090. {
  1091. pid_t pid;
  1092. int pipefd[2];
  1093. FILE *pf;
  1094. int tmp, flags;
  1095. char *ret = NULL;
  1096. if (pipe(pipefd) == -1)
  1097. printerr(1, "pipe(2)");
  1098. for (tmp = 0; tmp < 2; ++tmp) {
  1099. /* Get previous flags */
  1100. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1101. /* Set bit for non-blocking flag */
  1102. flags |= O_NONBLOCK;
  1103. /* Change flags on fd */
  1104. fcntl(pipefd[tmp], F_SETFL, flags);
  1105. }
  1106. pid = fork();
  1107. if (pid == 0) {
  1108. /* In child */
  1109. close(pipefd[0]);
  1110. dup2(pipefd[1], STDOUT_FILENO);
  1111. dup2(pipefd[1], STDERR_FILENO);
  1112. close(pipefd[1]);
  1113. execlp(file, file, arg1, arg2, NULL);
  1114. _exit(1);
  1115. }
  1116. /* In parent */
  1117. waitpid(pid, &tmp, 0);
  1118. close(pipefd[1]);
  1119. if (!pager) {
  1120. pf = fdopen(pipefd[0], "r");
  1121. if (pf) {
  1122. ret = fgets(buf, bytes, pf);
  1123. close(pipefd[0]);
  1124. }
  1125. return ret;
  1126. }
  1127. pid = fork();
  1128. if (pid == 0) {
  1129. /* Show in pager in child */
  1130. dup2(pipefd[0], STDIN_FILENO);
  1131. close(pipefd[0]);
  1132. execlp("less", "less", NULL);
  1133. _exit(1);
  1134. }
  1135. /* In parent */
  1136. waitpid(pid, &tmp, 0);
  1137. close(pipefd[0]);
  1138. return NULL;
  1139. }
  1140. /*
  1141. * Follows the stat(1) output closely
  1142. */
  1143. static int
  1144. show_stats(char *fpath, char *fname, struct stat *sb)
  1145. {
  1146. char *perms = get_lsperms(sb->st_mode, g_buf);
  1147. char *p, *begin = g_buf;
  1148. char tmp[] = "/tmp/nnnXXXXXX";
  1149. int fd = mkstemp(tmp);
  1150. if (fd == -1)
  1151. return -1;
  1152. /* Show file name or 'symlink' -> 'target' */
  1153. if (perms[0] == 'l') {
  1154. /* Note that MAX_CMD_LEN > PATH_MAX */
  1155. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1156. if (len != -1) {
  1157. g_buf[len] = '\0';
  1158. dprintf(fd, " File: '%s' -> ", unescape(fname));
  1159. dprintf(fd, "'%s'", unescape(g_buf));
  1160. xstrlcpy(g_buf, "symbolic link", MAX_CMD_LEN);
  1161. }
  1162. } else
  1163. dprintf(fd, " File: '%s'", unescape(fname));
  1164. /* Show size, blocks, file type */
  1165. #ifdef __APPLE__
  1166. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1167. #else
  1168. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1169. #endif
  1170. sb->st_size, sb->st_blocks, sb->st_blksize, g_buf);
  1171. /* Show containing device, inode, hardlink count */
  1172. #ifdef __APPLE__
  1173. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1174. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1175. #else
  1176. sprintf(g_buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  1177. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1178. #endif
  1179. g_buf, sb->st_ino, sb->st_nlink);
  1180. /* Show major, minor number for block or char device */
  1181. if (perms[0] == 'b' || perms[0] == 'c')
  1182. dprintf(fd, " Device type: %x,%x",
  1183. major(sb->st_rdev), minor(sb->st_rdev));
  1184. /* Show permissions, owner, group */
  1185. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)",
  1186. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7, sb->st_mode & 7,
  1187. perms,
  1188. sb->st_uid, (getpwuid(sb->st_uid))->pw_name,
  1189. sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1190. /* Show last access time */
  1191. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1192. dprintf(fd, "\n\n Access: %s", g_buf);
  1193. /* Show last modification time */
  1194. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1195. dprintf(fd, "\n Modify: %s", g_buf);
  1196. /* Show last status change time */
  1197. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1198. dprintf(fd, "\n Change: %s", g_buf);
  1199. if (S_ISREG(sb->st_mode)) {
  1200. /* Show file(1) output */
  1201. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1202. if (p) {
  1203. dprintf(fd, "\n\n ");
  1204. while (*p) {
  1205. if (*p == ',') {
  1206. *p = '\0';
  1207. dprintf(fd, " %s\n", begin);
  1208. begin = p + 1;
  1209. }
  1210. ++p;
  1211. }
  1212. dprintf(fd, " %s", begin);
  1213. }
  1214. dprintf(fd, "\n\n");
  1215. } else
  1216. dprintf(fd, "\n\n\n");
  1217. close(fd);
  1218. exitcurses();
  1219. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1220. unlink(tmp);
  1221. initcurses();
  1222. return 0;
  1223. }
  1224. static int
  1225. show_mediainfo(char *fpath, char *arg)
  1226. {
  1227. if (!get_output(g_buf, MAX_CMD_LEN, "which", metaviewer, NULL, 0))
  1228. return -1;
  1229. exitcurses();
  1230. get_output(NULL, 0, metaviewer, fpath, arg, 1);
  1231. initcurses();
  1232. return 0;
  1233. }
  1234. static int
  1235. show_help(void)
  1236. {
  1237. char tmp[] = "/tmp/nnnXXXXXX";
  1238. static char helpstr[] = ("\
  1239. Key | Function\n\
  1240. -+-\n\
  1241. Up, k, ^P | Previous entry\n\
  1242. Down, j, ^N | Next entry\n\
  1243. PgUp, ^U | Scroll half page up\n\
  1244. PgDn, ^D | Scroll half page down\n\
  1245. Home, g, ^, ^A | Jump to first entry\n\
  1246. End, G, $, ^E | Jump to last entry\n\
  1247. Right, Enter, l, ^M | Open file or enter dir\n\
  1248. Left, Bksp, h, ^H | Go to parent dir\n\
  1249. Insert | Toggle navigate-as-you-type mode\n\
  1250. ~ | Jump to HOME dir\n\
  1251. & | Jump to initial dir\n\
  1252. - | Jump to last visited dir\n\
  1253. / | Filter dir contents\n\
  1254. ^/ | Search dir in desktop search tool\n\
  1255. . | Toggle hide .dot files\n\
  1256. b | Show bookmark key prompt\n\
  1257. c | Show change dir prompt\n\
  1258. d | Toggle detail view\n\
  1259. D | Toggle current file details screen\n\
  1260. m | Show concise media info\n\
  1261. M | Show full media info\n\
  1262. s | Toggle sort by file size\n\
  1263. S | Toggle disk usage analyzer mode\n\
  1264. t | Toggle sort by modified time\n\
  1265. ! | Spawn SHELL in PWD (fallback sh)\n\
  1266. e | Edit entry in EDITOR (fallback vi)\n\
  1267. o | Open dir in NNN_DE_FILE_MANAGER\n\
  1268. p | Open entry in PAGER (fallback less)\n\
  1269. ^K | Invoke file path copier\n\
  1270. ^L, F2 | Force a redraw, exit filter prompt\n\
  1271. ? | Toggle help and settings screen\n\
  1272. Q | Quit and change directory\n\
  1273. q, ^Q | Quit\n\n\n");
  1274. int i = 0, fd = mkstemp(tmp);
  1275. if (fd == -1)
  1276. return -1;
  1277. dprintf(fd, "%s", helpstr);
  1278. if (getenv("NNN_BMS")) {
  1279. dprintf(fd, "BOOKMARKS\n");
  1280. for (; i < MAX_BM; ++i)
  1281. if (bookmark[i].key)
  1282. dprintf(fd, " %s: %s\n",
  1283. bookmark[i].key, bookmark[i].loc);
  1284. else
  1285. break;
  1286. dprintf(fd, "\n");
  1287. }
  1288. if (editor)
  1289. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1290. if (desktop_manager)
  1291. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1292. if (idletimeout)
  1293. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1294. if (copier)
  1295. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1296. dprintf(fd, "\n");
  1297. close(fd);
  1298. exitcurses();
  1299. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1300. unlink(tmp);
  1301. initcurses();
  1302. return 0;
  1303. }
  1304. static int
  1305. sum_bsizes(const char *fpath, const struct stat *sb,
  1306. int typeflag, struct FTW *ftwbuf)
  1307. {
  1308. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1309. ent_blocks += sb->st_blocks;
  1310. ++num_files;
  1311. return 0;
  1312. }
  1313. static int
  1314. getorder(size_t size)
  1315. {
  1316. switch (size) {
  1317. case 4096:
  1318. return 12;
  1319. case 512:
  1320. return 9;
  1321. case 8192:
  1322. return 13;
  1323. case 16384:
  1324. return 14;
  1325. case 32768:
  1326. return 15;
  1327. case 65536:
  1328. return 16;
  1329. case 131072:
  1330. return 17;
  1331. case 262144:
  1332. return 18;
  1333. case 524288:
  1334. return 19;
  1335. case 1048576:
  1336. return 20;
  1337. case 2048:
  1338. return 11;
  1339. case 1024:
  1340. return 10;
  1341. default:
  1342. return 0;
  1343. }
  1344. }
  1345. static int
  1346. dentfill(char *path, struct entry **dents,
  1347. int (*filter)(regex_t *, char *), regex_t *re)
  1348. {
  1349. static DIR *dirp;
  1350. static struct dirent *dp;
  1351. static struct stat sb;
  1352. static int fd, n;
  1353. n = 0;
  1354. if (cfg.blkorder) {
  1355. num_files = 0;
  1356. dir_blocks = 0;
  1357. }
  1358. dirp = opendir(path);
  1359. if (dirp == NULL)
  1360. return 0;
  1361. fd = dirfd(dirp);
  1362. while ((dp = readdir(dirp)) != NULL) {
  1363. /* Skip self and parent */
  1364. if ((dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
  1365. (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))))
  1366. continue;
  1367. if (filter(re, dp->d_name) == 0) {
  1368. if (!cfg.blkorder)
  1369. continue;
  1370. if (fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW)
  1371. == -1)
  1372. continue;
  1373. if (S_ISDIR(sb.st_mode)) {
  1374. ent_blocks = 0;
  1375. mkpath(path, dp->d_name, g_buf, PATH_MAX);
  1376. if (nftw(g_buf, sum_bsizes, open_max,
  1377. FTW_MOUNT | FTW_PHYS) == -1) {
  1378. printmsg("nftw(3) failed");
  1379. dir_blocks += sb.st_blocks;
  1380. } else
  1381. dir_blocks += ent_blocks;
  1382. } else {
  1383. if (sb.st_blocks)
  1384. dir_blocks += sb.st_blocks;
  1385. ++num_files;
  1386. }
  1387. continue;
  1388. }
  1389. if (fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1390. if (*dents)
  1391. free(*dents);
  1392. printerr(1, "fstatat");
  1393. }
  1394. if (n == total_dents) {
  1395. total_dents += 64;
  1396. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1397. if (*dents == NULL)
  1398. printerr(1, "realloc");
  1399. }
  1400. xstrlcpy((*dents)[n].name, dp->d_name, NAME_MAX);
  1401. (*dents)[n].mode = sb.st_mode;
  1402. (*dents)[n].t = sb.st_mtime;
  1403. (*dents)[n].size = sb.st_size;
  1404. if (cfg.blkorder) {
  1405. if (S_ISDIR(sb.st_mode)) {
  1406. ent_blocks = 0;
  1407. mkpath(path, dp->d_name, g_buf, PATH_MAX);
  1408. if (nftw(g_buf, sum_bsizes, open_max,
  1409. FTW_MOUNT | FTW_PHYS) == -1) {
  1410. printmsg("nftw(3) failed");
  1411. (*dents)[n].blocks = sb.st_blocks;
  1412. } else
  1413. (*dents)[n].blocks = ent_blocks;
  1414. } else {
  1415. (*dents)[n].blocks = sb.st_blocks;
  1416. ++num_files;
  1417. }
  1418. if ((*dents)[n].blocks)
  1419. dir_blocks += (*dents)[n].blocks;
  1420. }
  1421. ++n;
  1422. }
  1423. if (cfg.blkorder) {
  1424. static struct statvfs svb;
  1425. if (statvfs(path, &svb) == -1)
  1426. fs_free = 0;
  1427. else
  1428. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1429. }
  1430. /* Should never be null */
  1431. if (closedir(dirp) == -1) {
  1432. if (*dents)
  1433. free(*dents);
  1434. printerr(1, "closedir");
  1435. }
  1436. return n;
  1437. }
  1438. static void
  1439. dentfree(struct entry *dents)
  1440. {
  1441. free(dents);
  1442. }
  1443. /* Return the position of the matching entry or 0 otherwise */
  1444. static int
  1445. dentfind(struct entry *dents, int n, char *path)
  1446. {
  1447. if (!path)
  1448. return 0;
  1449. static int i;
  1450. static char *p;
  1451. p = basename(path);
  1452. DPRINTF_S(p);
  1453. for (i = 0; i < n; ++i)
  1454. if (xstrcmp(p, dents[i].name) == 0)
  1455. return i;
  1456. return 0;
  1457. }
  1458. static int
  1459. populate(char *path, char *oldpath, char *fltr)
  1460. {
  1461. static regex_t re;
  1462. /* Can fail when permissions change while browsing */
  1463. if (access(path, R_OK) == -1)
  1464. return -1;
  1465. /* Search filter */
  1466. if (setfilter(&re, fltr) != 0)
  1467. return -1;
  1468. if (cfg.blkorder) {
  1469. printmsg("Calculating...");
  1470. refresh();
  1471. }
  1472. ndents = dentfill(path, &dents, visible, &re);
  1473. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1474. /* Find cur from history */
  1475. cur = dentfind(dents, ndents, oldpath);
  1476. return 0;
  1477. }
  1478. static void
  1479. redraw(char *path)
  1480. {
  1481. static int nlines, i;
  1482. static size_t ncols;
  1483. nlines = MIN(LINES - 4, ndents);
  1484. /* Clean screen */
  1485. erase();
  1486. /* Strip trailing slashes */
  1487. for (i = xstrlen(path) - 1; i > 0; --i)
  1488. if (path[i] == '/')
  1489. path[i] = '\0';
  1490. else
  1491. break;
  1492. DPRINTF_D(cur);
  1493. DPRINTF_S(path);
  1494. /* No text wrapping in cwd line */
  1495. if (!realpath(path, g_buf)) {
  1496. printmsg("Cannot resolve path");
  1497. return;
  1498. }
  1499. ncols = COLS;
  1500. if (ncols > PATH_MAX)
  1501. ncols = PATH_MAX;
  1502. /* - xstrlen(CWD) - 1 = 6 */
  1503. g_buf[ncols - 6] = '\0';
  1504. printw(CWD "%s\n\n", g_buf);
  1505. if (cfg.showcolor) {
  1506. attron(COLOR_PAIR(1) | A_BOLD);
  1507. cfg.dircolor = 1;
  1508. }
  1509. /* Print listing */
  1510. if (cur < (nlines >> 1)) {
  1511. for (i = 0; i < nlines; ++i)
  1512. printptr(&dents[i], i == cur);
  1513. } else if (cur >= ndents - (nlines >> 1)) {
  1514. for (i = ndents - nlines; i < ndents; ++i)
  1515. printptr(&dents[i], i == cur);
  1516. } else {
  1517. static int odd;
  1518. odd = ISODD(nlines);
  1519. nlines >>= 1;
  1520. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1521. printptr(&dents[i], i == cur);
  1522. }
  1523. /* Must reset e.g. no files in dir */
  1524. if (cfg.dircolor) {
  1525. attroff(COLOR_PAIR(1) | A_BOLD);
  1526. cfg.dircolor = 0;
  1527. }
  1528. if (cfg.showdetail) {
  1529. if (ndents) {
  1530. static char ind[2] = "\0\0";
  1531. static char sort[9];
  1532. if (cfg.mtimeorder)
  1533. sprintf(sort, "by time ");
  1534. else if (cfg.sizeorder)
  1535. sprintf(sort, "by size ");
  1536. else
  1537. sort[0] = '\0';
  1538. if (S_ISDIR(dents[cur].mode))
  1539. ind[0] = '/';
  1540. else if (S_ISLNK(dents[cur].mode))
  1541. ind[0] = '@';
  1542. else if (S_ISSOCK(dents[cur].mode))
  1543. ind[0] = '=';
  1544. else if (S_ISFIFO(dents[cur].mode))
  1545. ind[0] = '|';
  1546. else if (dents[cur].mode & 0100)
  1547. ind[0] = '*';
  1548. else
  1549. ind[0] = '\0';
  1550. /* We need to show filename as it may
  1551. * be truncated in directory listing
  1552. */
  1553. if (!cfg.blkorder)
  1554. sprintf(g_buf, "total %d %s[%s%s]", ndents,
  1555. sort, unescape(dents[cur].name), ind);
  1556. else {
  1557. i = sprintf(g_buf, "du: %s (%lu files) ",
  1558. coolsize(dir_blocks << 9),
  1559. num_files);
  1560. sprintf(g_buf + i, "vol: %s free [%s%s]",
  1561. coolsize(fs_free),
  1562. unescape(dents[cur].name), ind);
  1563. }
  1564. printmsg(g_buf);
  1565. } else
  1566. printmsg("0 items");
  1567. }
  1568. }
  1569. static void
  1570. browse(char *ipath, char *ifilter)
  1571. {
  1572. char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  1573. char lastdir[PATH_MAX];
  1574. char fltr[LINE_MAX];
  1575. char *dir, *tmp, *run, *env, *tgt=NULL;
  1576. struct stat sb;
  1577. int r, fd, presel;
  1578. enum action sel = SEL_RUNARG + 1;
  1579. xstrlcpy(path, ipath, PATH_MAX);
  1580. xstrlcpy(fltr, ifilter, LINE_MAX);
  1581. oldpath[0] = '\0';
  1582. newpath[0] = '\0';
  1583. lastdir[0] = '\0'; /* Can't move back from initial directory */
  1584. if (cfg.filtermode)
  1585. presel = FILTER;
  1586. else
  1587. presel = 0;
  1588. begin:
  1589. if (populate(path, oldpath, fltr) == -1) {
  1590. printwarn();
  1591. goto nochange;
  1592. }
  1593. for (;;) {
  1594. redraw(path);
  1595. nochange:
  1596. /* Exit if parent has exited */
  1597. if (getppid() == 1)
  1598. _exit(0);
  1599. sel = nextsel(&run, &env, &presel);
  1600. switch (sel) {
  1601. case SEL_CDQUIT:
  1602. {
  1603. char *tmpfile = "/tmp/nnn";
  1604. tmp = getenv("NNN_TMPFILE");
  1605. if (tmp)
  1606. tmpfile = tmp;
  1607. FILE *fp = fopen(tmpfile, "w");
  1608. if (fp) {
  1609. fprintf(fp, "cd \"%s\"", path);
  1610. fclose(fp);
  1611. }
  1612. /* Fall through to exit */
  1613. } // fallthrough
  1614. case SEL_QUIT:
  1615. dentfree(dents);
  1616. return;
  1617. case SEL_BACK:
  1618. /* There is no going back */
  1619. if (path[0] == '/' && path[1] == '\0') {
  1620. printmsg("You are at /");
  1621. goto nochange;
  1622. }
  1623. dir = xdirname(path);
  1624. if (access(dir, R_OK) == -1) {
  1625. printwarn();
  1626. goto nochange;
  1627. }
  1628. /* Save history */
  1629. xstrlcpy(oldpath, path, PATH_MAX);
  1630. /* Save last working directory */
  1631. xstrlcpy(lastdir, path, PATH_MAX);
  1632. xstrlcpy(path, dir, PATH_MAX);
  1633. /* Reset filter */
  1634. xstrlcpy(fltr, ifilter, LINE_MAX);
  1635. if (cfg.filtermode)
  1636. presel = FILTER;
  1637. goto begin;
  1638. case SEL_GOIN:
  1639. /* Cannot descend in empty directories */
  1640. if (ndents == 0)
  1641. goto begin;
  1642. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1643. DPRINTF_S(newpath);
  1644. /* Get path info */
  1645. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1646. if (fd == -1) {
  1647. printwarn();
  1648. goto nochange;
  1649. }
  1650. r = fstat(fd, &sb);
  1651. if (r == -1) {
  1652. printwarn();
  1653. close(fd);
  1654. goto nochange;
  1655. }
  1656. close(fd);
  1657. DPRINTF_U(sb.st_mode);
  1658. switch (sb.st_mode & S_IFMT) {
  1659. case S_IFDIR:
  1660. if (access(newpath, R_OK) == -1) {
  1661. printwarn();
  1662. goto nochange;
  1663. }
  1664. /* Save last working directory */
  1665. xstrlcpy(lastdir, path, PATH_MAX);
  1666. xstrlcpy(path, newpath, PATH_MAX);
  1667. oldpath[0] = '\0';
  1668. /* Reset filter */
  1669. xstrlcpy(fltr, ifilter, LINE_MAX);
  1670. if (cfg.filtermode)
  1671. presel = FILTER;
  1672. goto begin;
  1673. case S_IFREG:
  1674. {
  1675. /* If NNN_USE_EDITOR is set,
  1676. * open text in EDITOR
  1677. */
  1678. if (editor) {
  1679. if (getmime(dents[cur].name)) {
  1680. spawn(editor, newpath, NULL,
  1681. NULL, F_NORMAL);
  1682. continue;
  1683. }
  1684. /* Recognize and open plain
  1685. * text files with vi
  1686. */
  1687. if (get_output(g_buf, MAX_CMD_LEN,
  1688. "file", "-bi",
  1689. newpath, 0) == NULL)
  1690. continue;
  1691. if (strstr(g_buf, "text/") == g_buf) {
  1692. spawn(editor, newpath, NULL,
  1693. NULL, F_NORMAL);
  1694. continue;
  1695. }
  1696. }
  1697. /* Invoke desktop opener as last resort */
  1698. spawn(utils[0], newpath, NULL, NULL, F_NOTRACE);
  1699. continue;
  1700. }
  1701. default:
  1702. printmsg("Unsupported file");
  1703. goto nochange;
  1704. }
  1705. case SEL_FLTR:
  1706. presel = readln(path);
  1707. xstrlcpy(fltr, ifilter, LINE_MAX);
  1708. DPRINTF_S(fltr);
  1709. /* Save current */
  1710. if (ndents > 0)
  1711. mkpath(path, dents[cur].name, oldpath,
  1712. PATH_MAX);
  1713. goto nochange;
  1714. case SEL_MFLTR:
  1715. cfg.filtermode ^= 1;
  1716. if (cfg.filtermode)
  1717. presel = FILTER;
  1718. else
  1719. printmsg("navigate-as-you-type off");
  1720. goto nochange;
  1721. case SEL_SEARCH:
  1722. spawn(player, path, "search", NULL, F_NORMAL);
  1723. break;
  1724. case SEL_NEXT:
  1725. if (cur < ndents - 1)
  1726. ++cur;
  1727. else if (ndents)
  1728. /* Roll over, set cursor to first entry */
  1729. cur = 0;
  1730. break;
  1731. case SEL_PREV:
  1732. if (cur > 0)
  1733. --cur;
  1734. else if (ndents)
  1735. /* Roll over, set cursor to last entry */
  1736. cur = ndents - 1;
  1737. break;
  1738. case SEL_PGDN:
  1739. if (cur < ndents - 1)
  1740. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1741. break;
  1742. case SEL_PGUP:
  1743. if (cur > 0)
  1744. cur -= MIN((LINES - 4) / 2, cur);
  1745. break;
  1746. case SEL_HOME:
  1747. cur = 0;
  1748. break;
  1749. case SEL_END:
  1750. cur = ndents - 1;
  1751. break;
  1752. case SEL_CD:
  1753. {
  1754. static char *input;
  1755. static int truecd;
  1756. /* Save the program start dir */
  1757. tmp = getcwd(newpath, PATH_MAX);
  1758. if (tmp == NULL) {
  1759. printwarn();
  1760. goto nochange;
  1761. }
  1762. /* Switch to current path for readline(3) */
  1763. if (chdir(path) == -1) {
  1764. printwarn();
  1765. goto nochange;
  1766. }
  1767. exitcurses();
  1768. tmp = readline("chdir: ");
  1769. initcurses();
  1770. /* Change back to program start dir */
  1771. if (chdir(newpath) == -1)
  1772. printwarn();
  1773. if (tmp[0] == '\0')
  1774. break;
  1775. /* Add to readline(3) history */
  1776. add_history(tmp);
  1777. input = tmp;
  1778. tmp = strstrip(tmp);
  1779. if (tmp[0] == '\0') {
  1780. free(input);
  1781. break;
  1782. }
  1783. truecd = 0;
  1784. if (tmp[0] == '~') {
  1785. /* Expand ~ to HOME absolute path */
  1786. char *home = getenv("HOME");
  1787. if (home)
  1788. snprintf(newpath, PATH_MAX, "%s%s",
  1789. home, tmp + 1);
  1790. else {
  1791. free(input);
  1792. printmsg("HOME not set");
  1793. goto nochange;
  1794. }
  1795. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1796. if (lastdir[0] == '\0') {
  1797. free(input);
  1798. break;
  1799. }
  1800. /* Switch to last visited dir */
  1801. xstrlcpy(newpath, lastdir, PATH_MAX);
  1802. truecd = 1;
  1803. } else if ((r = all_dots(tmp))) {
  1804. if (r == 1) {
  1805. /* Always in the current dir */
  1806. free(input);
  1807. break;
  1808. }
  1809. /* Show a message if already at / */
  1810. if (path[0] == '/' && path[1] == '\0') {
  1811. printmsg("You are at /");
  1812. free(input);
  1813. goto nochange;
  1814. }
  1815. --r; /* One . for the current dir */
  1816. dir = path;
  1817. /* Note: fd is used as a tmp variable here */
  1818. for (fd = 0; fd < r; ++fd) {
  1819. /* Reached / ? */
  1820. if (path[0] == '/' && path[1] == '\0') {
  1821. /* Can't cd beyond / */
  1822. break;
  1823. }
  1824. dir = xdirname(dir);
  1825. if (access(dir, R_OK) == -1) {
  1826. printwarn();
  1827. free(input);
  1828. goto nochange;
  1829. }
  1830. }
  1831. truecd = 1;
  1832. /* Save the path in case of cd ..
  1833. * We mark the current dir in parent dir
  1834. */
  1835. if (r == 1) {
  1836. xstrlcpy(oldpath, path, PATH_MAX);
  1837. truecd = 2;
  1838. }
  1839. xstrlcpy(newpath, dir, PATH_MAX);
  1840. } else
  1841. mkpath(path, tmp, newpath, PATH_MAX);
  1842. free(input);
  1843. if (access(newpath, R_OK) == -1) {
  1844. printwarn();
  1845. break;
  1846. }
  1847. if (truecd == 0) {
  1848. /* Probable change in dir */
  1849. /* No-op if it's the same directory */
  1850. if (xstrcmp(path, newpath) == 0)
  1851. break;
  1852. oldpath[0] = '\0';
  1853. } else if (truecd == 1)
  1854. /* Sure change in dir */
  1855. oldpath[0] = '\0';
  1856. /* Save last working directory */
  1857. xstrlcpy(lastdir, path, PATH_MAX);
  1858. /* Save the newly opted dir in path */
  1859. xstrlcpy(path, newpath, PATH_MAX);
  1860. /* Reset filter */
  1861. xstrlcpy(fltr, ifilter, LINE_MAX);
  1862. DPRINTF_S(path);
  1863. if (cfg.filtermode)
  1864. presel = FILTER;
  1865. goto begin;
  1866. }
  1867. case SEL_CDHOME:
  1868. tgt = getenv("HOME");
  1869. if (tgt == NULL) {
  1870. clearprompt();
  1871. goto nochange;
  1872. } // fallthrough
  1873. case SEL_CDBEGIN:
  1874. if (!tgt)
  1875. tgt = ipath;
  1876. if (access(tgt, R_OK) == -1) {
  1877. printwarn();
  1878. tgt = NULL;
  1879. goto nochange;
  1880. }
  1881. if (xstrcmp(path, tgt) == 0) {
  1882. tgt = NULL;
  1883. break;
  1884. }
  1885. /* Save last working directory */
  1886. xstrlcpy(lastdir, path, PATH_MAX);
  1887. xstrlcpy(path, tgt, PATH_MAX);
  1888. oldpath[0] = '\0';
  1889. /* Reset filter */
  1890. xstrlcpy(fltr, ifilter, LINE_MAX);
  1891. DPRINTF_S(path);
  1892. if (cfg.filtermode)
  1893. presel = FILTER;
  1894. tgt = NULL;
  1895. goto begin;
  1896. case SEL_CDLAST:
  1897. if (lastdir[0] == '\0') {
  1898. printmsg("Hit end of history...");
  1899. goto nochange;
  1900. }
  1901. if (access(lastdir, R_OK) == -1) {
  1902. printwarn();
  1903. goto nochange;
  1904. }
  1905. xstrlcpy(newpath, lastdir, PATH_MAX);
  1906. xstrlcpy(lastdir, path, PATH_MAX);
  1907. xstrlcpy(path, newpath, PATH_MAX);
  1908. oldpath[0] = '\0';
  1909. /* Reset filter */
  1910. xstrlcpy(fltr, ifilter, LINE_MAX);
  1911. DPRINTF_S(path);
  1912. if (cfg.filtermode)
  1913. presel = FILTER;
  1914. goto begin;
  1915. case SEL_CDBM:
  1916. printprompt("key: ");
  1917. tmp = readinput();
  1918. clearprompt();
  1919. if (tmp == NULL)
  1920. goto nochange;
  1921. for (r = 0; bookmark[r].key && r < MAX_BM; ++r) {
  1922. if (xstrcmp(bookmark[r].key, tmp) == -1)
  1923. continue;
  1924. if (bookmark[r].loc[0] == '~') {
  1925. /* Expand ~ to HOME */
  1926. char *home = getenv("HOME");
  1927. if (home)
  1928. snprintf(newpath,
  1929. PATH_MAX,
  1930. "%s%s",
  1931. home,
  1932. bookmark[r].loc
  1933. + 1);
  1934. else {
  1935. printmsg("HOME not set");
  1936. goto nochange;
  1937. }
  1938. } else
  1939. mkpath(path, bookmark[r].loc,
  1940. newpath, PATH_MAX);
  1941. if (access(newpath, R_OK) == -1) {
  1942. printwarn();
  1943. goto nochange;
  1944. }
  1945. if (xstrcmp(path, newpath) == 0)
  1946. break;
  1947. oldpath[0] = '\0';
  1948. break;
  1949. }
  1950. if (!bookmark[r].key) {
  1951. printmsg("No matching bookmark");
  1952. goto nochange;
  1953. }
  1954. /* Save last working directory */
  1955. xstrlcpy(lastdir, path, PATH_MAX);
  1956. /* Save the newly opted dir in path */
  1957. xstrlcpy(path, newpath, PATH_MAX);
  1958. /* Reset filter */
  1959. xstrlcpy(fltr, ifilter, LINE_MAX);
  1960. DPRINTF_S(path);
  1961. if (cfg.filtermode)
  1962. presel = FILTER;
  1963. goto begin;
  1964. case SEL_TOGGLEDOT:
  1965. cfg.showhidden ^= 1;
  1966. initfilter(cfg.showhidden, &ifilter);
  1967. xstrlcpy(fltr, ifilter, LINE_MAX);
  1968. goto begin;
  1969. case SEL_DETAIL:
  1970. cfg.showdetail ^= 1;
  1971. cfg.showdetail ? (printptr = &printent_long)
  1972. : (printptr = &printent);
  1973. /* Save current */
  1974. if (ndents > 0)
  1975. mkpath(path, dents[cur].name, oldpath,
  1976. PATH_MAX);
  1977. goto begin;
  1978. case SEL_STATS:
  1979. {
  1980. struct stat sb;
  1981. if (ndents > 0) {
  1982. mkpath(path, dents[cur].name, oldpath,
  1983. PATH_MAX);
  1984. r = lstat(oldpath, &sb);
  1985. if (r == -1) {
  1986. if (dents)
  1987. dentfree(dents);
  1988. printerr(1, "lstat");
  1989. } else {
  1990. r = show_stats(oldpath, dents[cur].name,
  1991. &sb);
  1992. if (r < 0) {
  1993. printmsg(strerror(errno));
  1994. goto nochange;
  1995. }
  1996. }
  1997. }
  1998. break;
  1999. }
  2000. case SEL_MEDIA: // fallthrough
  2001. case SEL_FMEDIA:
  2002. if (ndents > 0) {
  2003. mkpath(path, dents[cur].name, oldpath,
  2004. PATH_MAX);
  2005. if (show_mediainfo(oldpath, run) == -1) {
  2006. sprintf(g_buf, "%s missing", metaviewer);
  2007. printmsg(g_buf);
  2008. goto nochange;
  2009. }
  2010. }
  2011. break;
  2012. case SEL_DFB:
  2013. if (!desktop_manager) {
  2014. printmsg("NNN_DE_FILE_MANAGER not set");
  2015. goto nochange;
  2016. }
  2017. spawn(desktop_manager, path, NULL, path,
  2018. F_NOTRACE | F_NOWAIT);
  2019. break;
  2020. case SEL_FSIZE:
  2021. cfg.sizeorder ^= 1;
  2022. cfg.mtimeorder = 0;
  2023. cfg.blkorder = 0;
  2024. /* Save current */
  2025. if (ndents > 0)
  2026. mkpath(path, dents[cur].name, oldpath,
  2027. PATH_MAX);
  2028. goto begin;
  2029. case SEL_BSIZE:
  2030. cfg.blkorder ^= 1;
  2031. if (cfg.blkorder) {
  2032. cfg.showdetail = 1;
  2033. printptr = &printent_long;
  2034. }
  2035. cfg.mtimeorder = 0;
  2036. cfg.sizeorder = 0;
  2037. /* Save current */
  2038. if (ndents > 0)
  2039. mkpath(path, dents[cur].name, oldpath,
  2040. PATH_MAX);
  2041. goto begin;
  2042. case SEL_MTIME:
  2043. cfg.mtimeorder ^= 1;
  2044. cfg.sizeorder = 0;
  2045. cfg.blkorder = 0;
  2046. /* Save current */
  2047. if (ndents > 0)
  2048. mkpath(path, dents[cur].name, oldpath,
  2049. PATH_MAX);
  2050. goto begin;
  2051. case SEL_REDRAW:
  2052. /* Save current */
  2053. if (ndents > 0)
  2054. mkpath(path, dents[cur].name, oldpath,
  2055. PATH_MAX);
  2056. goto begin;
  2057. case SEL_COPY:
  2058. if (copier && ndents) {
  2059. if (path[0] == '/' && path[1] == '\0')
  2060. snprintf(newpath, PATH_MAX, "/%s",
  2061. dents[cur].name);
  2062. else
  2063. snprintf(newpath, PATH_MAX, "%s/%s",
  2064. path, dents[cur].name);
  2065. spawn(copier, newpath, NULL, NULL, F_NONE);
  2066. printmsg(newpath);
  2067. } else if (!copier)
  2068. printmsg("NNN_COPIER is not set");
  2069. goto nochange;
  2070. case SEL_HELP:
  2071. show_help();
  2072. break;
  2073. case SEL_RUN:
  2074. run = xgetenv(env, run);
  2075. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2076. /* Repopulate as directory content may have changed */
  2077. goto begin;
  2078. case SEL_RUNARG:
  2079. run = xgetenv(env, run);
  2080. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2081. break;
  2082. }
  2083. /* Screensaver */
  2084. if (idletimeout != 0 && idle == idletimeout) {
  2085. idle = 0;
  2086. spawn(player, "", "screensaver", NULL,
  2087. F_NORMAL | F_SIGINT);
  2088. }
  2089. }
  2090. }
  2091. static void
  2092. usage(void)
  2093. {
  2094. printf("usage: nnn [-l] [-i] [-p custom_nlay] [-S] [-v] [-h] [PATH]\n\n\
  2095. The missing terminal file browser for X.\n\n\
  2096. positional arguments:\n\
  2097. PATH directory to open [default: current dir]\n\n\
  2098. optional arguments:\n\
  2099. -c N specify dir color, disables if N>7\n\
  2100. -e use exiftool instead of mediainfo\n\
  2101. -i start in navigate-as-you-type mode\n\
  2102. -l start in light mode (fewer details)\n\
  2103. -n disable color for directory entries\n\
  2104. -p path to custom nlay\n\
  2105. -S start in disk usage analyzer mode\n\
  2106. -v show program version and exit\n\
  2107. -h show this help and exit\n\n\
  2108. Version: %s\n\
  2109. License: BSD 2-Clause\n\
  2110. Webpage: https://github.com/jarun/nnn\n", VERSION);
  2111. exit(0);
  2112. }
  2113. int
  2114. main(int argc, char *argv[])
  2115. {
  2116. char cwd[PATH_MAX], *ipath;
  2117. char *ifilter, *bmstr;
  2118. int opt;
  2119. /* Confirm we are in a terminal */
  2120. if (!isatty(0) || !isatty(1)) {
  2121. fprintf(stderr, "stdin or stdout is not a tty\n");
  2122. exit(1);
  2123. }
  2124. while ((opt = getopt(argc, argv, "Slic:ep:vh")) != -1) {
  2125. switch (opt) {
  2126. case 'S':
  2127. cfg.blkorder = 1;
  2128. break;
  2129. case 'l':
  2130. cfg.showdetail = 0;
  2131. printptr = &printent;
  2132. break;
  2133. case 'i':
  2134. cfg.filtermode = 1;
  2135. break;
  2136. case 'c':
  2137. color = (uchar)atoi(optarg);
  2138. if (color > 7)
  2139. cfg.showcolor = 0;
  2140. break;
  2141. case 'e':
  2142. metaviewer = utils[3];
  2143. break;
  2144. case 'p':
  2145. player = optarg;
  2146. break;
  2147. case 'v':
  2148. printf("%s\n", VERSION);
  2149. return 0;
  2150. case 'h': // fallthrough
  2151. default:
  2152. usage();
  2153. }
  2154. }
  2155. if (argc == optind) {
  2156. /* Start in the current directory */
  2157. ipath = getcwd(cwd, PATH_MAX);
  2158. if (ipath == NULL)
  2159. ipath = "/";
  2160. } else {
  2161. ipath = realpath(argv[optind], cwd);
  2162. if (!ipath) {
  2163. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2164. exit(1);
  2165. }
  2166. }
  2167. /* Increase current open file descriptor limit */
  2168. open_max = max_openfds();
  2169. if (getuid() == 0)
  2170. cfg.showhidden = 1;
  2171. initfilter(cfg.showhidden, &ifilter);
  2172. /* Parse bookmarks string, if available */
  2173. bmstr = getenv("NNN_BMS");
  2174. if (bmstr)
  2175. parsebmstr(bmstr);
  2176. /* Edit text in EDITOR, if opted */
  2177. if (getenv("NNN_USE_EDITOR"))
  2178. editor = xgetenv("EDITOR", "vi");
  2179. /* Set metadata viewer if not set */
  2180. if (!metaviewer)
  2181. metaviewer = utils[2];
  2182. /* Set player if not set already */
  2183. if (!player)
  2184. player = utils[1];
  2185. /* Get the desktop file browser, if set */
  2186. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2187. /* Get screensaver wait time, if set; copier used as tmp var */
  2188. copier = getenv("NNN_IDLE_TIMEOUT");
  2189. if (copier)
  2190. idletimeout = abs(atoi(copier));
  2191. /* Get the default copier, if set */
  2192. copier = getenv("NNN_COPIER");
  2193. signal(SIGINT, SIG_IGN);
  2194. /* Test initial path */
  2195. if (access(ipath, R_OK) == -1) {
  2196. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2197. exit(1);
  2198. }
  2199. /* Set locale */
  2200. setlocale(LC_ALL, "");
  2201. #ifdef DEBUGMODE
  2202. enabledbg();
  2203. #endif
  2204. initcurses();
  2205. browse(ipath, ifilter);
  2206. exitcurses();
  2207. #ifdef DEBUGMODE
  2208. disabledbg();
  2209. #endif
  2210. exit(0);
  2211. }