My build of nnn with minor changes
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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