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