My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

nnn.c 61 KiB

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