My build of nnn with minor changes
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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