My build of nnn with minor changes
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

nnn.c 77 KiB

7年前
8年前
8年前
8年前
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541
  1. /*
  2. * BSD 2-Clause License
  3. *
  4. * Copyright (c) 2014-2016, Lazaros Koromilas <lostd@2f30.org>
  5. * Copyright (c) 2014-2016, Dimitris Papastamos <sin@2f30.org>
  6. * Copyright (c) 2016-2018, Arun Prakash Jana <engineerarun@gmail.com>
  7. * All rights reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions are met:
  11. *
  12. * * Redistributions of source code must retain the above copyright notice, this
  13. * list of conditions and the following disclaimer.
  14. *
  15. * * Redistributions in binary form must reproduce the above copyright notice,
  16. * this list of conditions and the following disclaimer in the documentation
  17. * and/or other materials provided with the distribution.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  20. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  23. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  24. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  25. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  26. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  27. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #ifdef __linux__
  31. #ifdef __i386__
  32. #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit Linux */
  33. #endif
  34. #include <sys/inotify.h>
  35. #define LINUX_INOTIFY
  36. #if !defined(__GLIBC__)
  37. #include <sys/types.h>
  38. #endif
  39. #endif
  40. #include <sys/resource.h>
  41. #include <sys/stat.h>
  42. #include <sys/statvfs.h>
  43. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  44. #include <sys/types.h>
  45. #include <sys/event.h>
  46. #include <sys/time.h>
  47. #define BSD_KQUEUE
  48. #else
  49. #include <sys/sysmacros.h>
  50. #endif
  51. #include <sys/wait.h>
  52. #include <ctype.h>
  53. #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
  54. #ifndef NCURSES_WIDECHAR
  55. #define NCURSES_WIDECHAR 1
  56. #endif
  57. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  58. #ifndef _XOPEN_SOURCE_EXTENDED
  59. #define _XOPEN_SOURCE_EXTENDED
  60. #endif
  61. #endif
  62. #ifndef __USE_XOPEN /* Fix failure due to wcswidth(), ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
  63. #define __USE_XOPEN
  64. #endif
  65. #include <curses.h>
  66. #include <dirent.h>
  67. #include <errno.h>
  68. #include <fcntl.h>
  69. #include <grp.h>
  70. #include <libgen.h>
  71. #include <limits.h>
  72. #ifdef __gnu_hurd__
  73. #define PATH_MAX 4096
  74. #endif
  75. #include <locale.h>
  76. #include <pwd.h>
  77. #include <regex.h>
  78. #include <signal.h>
  79. #include <stdarg.h>
  80. #include <stdio.h>
  81. #include <stdlib.h>
  82. #include <string.h>
  83. #include <strings.h>
  84. #include <time.h>
  85. #include <unistd.h>
  86. #ifndef __USE_XOPEN_EXTENDED
  87. #define __USE_XOPEN_EXTENDED 1
  88. #endif
  89. #include <ftw.h>
  90. #include <wchar.h>
  91. #include "nnn.h"
  92. #ifdef DEBUGMODE
  93. static int DEBUG_FD;
  94. static int
  95. xprintf(int fd, const char *fmt, ...)
  96. {
  97. char buf[BUFSIZ];
  98. int r;
  99. va_list ap;
  100. va_start(ap, fmt);
  101. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  102. if (r > 0)
  103. r = write(fd, buf, r);
  104. va_end(ap);
  105. return r;
  106. }
  107. static int
  108. enabledbg()
  109. {
  110. FILE *fp = fopen("/tmp/nnn_debug", "w");
  111. if (!fp) {
  112. fprintf(stderr, "debug: open failed! (1)\n");
  113. fp = fopen("./nnn_debug", "w");
  114. if (!fp) {
  115. fprintf(stderr, "debug: open failed! (2)\n");
  116. return -1;
  117. }
  118. }
  119. DEBUG_FD = fileno(fp);
  120. if (DEBUG_FD == -1) {
  121. fprintf(stderr, "debug: open fd failed!\n");
  122. return -1;
  123. }
  124. return 0;
  125. }
  126. static void
  127. disabledbg()
  128. {
  129. close(DEBUG_FD);
  130. }
  131. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  132. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  133. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  134. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=%p\n", x)
  135. #else
  136. #define DPRINTF_D(x)
  137. #define DPRINTF_U(x)
  138. #define DPRINTF_S(x)
  139. #define DPRINTF_P(x)
  140. #endif /* DEBUGMODE */
  141. /* Macro definitions */
  142. #define VERSION "1.9"
  143. #define GENERAL_INFO "License: BSD 2-Clause\nWebpage: https://github.com/jarun/nnn"
  144. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  145. #undef MIN
  146. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  147. #define ISODD(x) ((x) & 1)
  148. #define TOUPPER(ch) \
  149. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  150. #define MAX_CMD_LEN 5120
  151. #define CURSR " > "
  152. #define EMPTY " "
  153. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  154. #define FILTER '/'
  155. #define REGEX_MAX 128
  156. #define BM_MAX 10
  157. #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
  158. #define NAMEBUF_INCR 0x1000 /* 64 dir entries at a time, avg. 64 chars per filename = 64*64B = 4KB */
  159. #define DESCRIPTOR_LEN 32
  160. #define _ALIGNMENT 0x10
  161. #define _ALIGNMENT_MASK 0xF
  162. #define SYMLINK_TO_DIR 0x1
  163. #define MAX_HOME_LEN 64
  164. /* Macros to define process spawn behaviour as flags */
  165. #define F_NONE 0x00 /* no flag set */
  166. #define F_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
  167. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  168. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  169. #define F_SIGINT 0x08 /* restore default SIGINT handler */
  170. #define F_NORMAL 0x80 /* spawn child process in non-curses regular CLI mode */
  171. /* CRC8 macros */
  172. #define WIDTH (sizeof(unsigned char) << 3)
  173. #define TOPBIT (1 << (WIDTH - 1))
  174. #define POLYNOMIAL 0xD8 /* 11011 followed by 0's */
  175. #define CRC8_TABLE_LEN 256
  176. /* Volume info */
  177. #define FREE 0
  178. #define CAPACITY 1
  179. /* Function macros */
  180. #define exitcurses() endwin()
  181. #define clearprompt() printmsg("")
  182. #define printwarn() printmsg(strerror(errno))
  183. #define istopdir(path) (path[1] == '\0' && path[0] == '/')
  184. #define copyfilter() xstrlcpy(fltr, ifilter, NAME_MAX)
  185. #define copycurname() xstrlcpy(oldname, dents[cur].name, NAME_MAX + 1)
  186. #define settimeout() timeout(1000)
  187. #define cleartimeout() timeout(-1)
  188. #define errexit() printerr(__LINE__)
  189. #ifdef LINUX_INOTIFY
  190. #define EVENT_SIZE (sizeof(struct inotify_event))
  191. #define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
  192. #elif defined(BSD_KQUEUE)
  193. #define NUM_EVENT_SLOTS 1
  194. #define NUM_EVENT_FDS 1
  195. #endif
  196. /* TYPE DEFINITIONS */
  197. typedef unsigned long ulong;
  198. typedef unsigned int uint;
  199. typedef unsigned char uchar;
  200. typedef unsigned short ushort;
  201. /* STRUCTURES */
  202. /* Directory entry */
  203. typedef struct entry {
  204. char *name;
  205. time_t t;
  206. off_t size;
  207. blkcnt_t blocks; /* number of 512B blocks allocated */
  208. mode_t mode;
  209. ushort nlen; /* Length of file name; can be uchar (< NAME_MAX + 1) */
  210. uchar flags; /* Flags specific to the file */
  211. } __attribute__ ((packed, aligned(_ALIGNMENT))) *pEntry;
  212. /* Bookmark */
  213. typedef struct {
  214. char *key;
  215. char *loc;
  216. } bm;
  217. /* Settings */
  218. typedef struct {
  219. ushort filtermode : 1; /* Set to enter filter mode */
  220. ushort mtimeorder : 1; /* Set to sort by time modified */
  221. ushort sizeorder : 1; /* Set to sort by file size */
  222. ushort apparentsz : 1; /* Set to sort by apparent size (disk usage) */
  223. ushort blkorder : 1; /* Set to sort by blocks used (disk usage) */
  224. ushort showhidden : 1; /* Set to show hidden files */
  225. ushort copymode : 1; /* Set when copying files */
  226. ushort showdetail : 1; /* Clear to show fewer file info */
  227. ushort showcolor : 1; /* Set to show dirs in blue */
  228. ushort dircolor : 1; /* Current status of dir color */
  229. ushort metaviewer : 1; /* Index of metadata viewer in utils[] */
  230. ushort quote : 1; /* Copy paths within quotes */
  231. ushort noxdisplay : 1; /* X11 is not available */
  232. ushort color : 3; /* Color code for directories */
  233. } settings;
  234. /* GLOBALS */
  235. /* Configuration */
  236. static settings cfg = {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 4};
  237. static struct entry *dents;
  238. static char *pnamebuf, *pcopybuf;
  239. static int ndents, cur, total_dents = ENTRY_INCR;
  240. static uint idle;
  241. static uint idletimeout, copybufpos, copybuflen;
  242. static char *player;
  243. static char *copier;
  244. static char *editor;
  245. static char *dmanager; /* desktop file manager */
  246. static blkcnt_t ent_blocks;
  247. static blkcnt_t dir_blocks;
  248. static ulong num_files;
  249. static uint open_max;
  250. static bm bookmark[BM_MAX];
  251. static uchar BLK_SHIFT = 9;
  252. static uchar crc8table[CRC8_TABLE_LEN] __attribute__ ((aligned));
  253. static uchar g_crc;
  254. #ifdef LINUX_INOTIFY
  255. static int inotify_fd, inotify_wd = -1;
  256. static uint INOTIFY_MASK = IN_ATTRIB | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  257. #elif defined(BSD_KQUEUE)
  258. static int kq, event_fd = -1;
  259. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  260. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  261. static struct timespec gtimeout;
  262. #endif
  263. /* Macros for utilities */
  264. #define MEDIAINFO 0
  265. #define EXIFTOOL 1
  266. #define OPENER 2
  267. #define NLAY 3
  268. #define ATOOL 4
  269. #define APACK 5
  270. #define VIDIR 6
  271. #define UNKNOWN 7
  272. /* Utilities to open files, run actions */
  273. static char * const utils[] = {
  274. "mediainfo",
  275. "exiftool",
  276. #ifdef __APPLE__
  277. "/usr/bin/open",
  278. #elif defined __CYGWIN__
  279. "cygstart",
  280. #else
  281. "xdg-open",
  282. #endif
  283. "nlay",
  284. "atool",
  285. "apack",
  286. "vidir",
  287. "UNKNOWN"
  288. };
  289. /* Common strings */
  290. #define STR_NFTWFAIL_ID 0
  291. #define STR_NOHOME_ID 1
  292. #define STR_INPUT_ID 2
  293. #define STR_INVBM_ID 3
  294. #define STR_COPY_ID 4
  295. #define STR_DATE_ID 5
  296. static const char messages[][16] = {
  297. "nftw failed",
  298. "HOME not set",
  299. "no traversal",
  300. "invalid key",
  301. "copy not set",
  302. "%F %T %z",
  303. };
  304. /* For use in functions which are isolated and don't return the buffer */
  305. static char g_buf[MAX_CMD_LEN] __attribute__ ((aligned));
  306. /* Buffer for file path copy file */
  307. static char g_cppath[MAX_HOME_LEN] __attribute__ ((aligned));
  308. /* Buffer to store HOME path, for help and file details */
  309. static char g_homepath[MAX_HOME_LEN] __attribute__ ((aligned));
  310. static size_t g_homelen;
  311. /* Forward declarations */
  312. static void redraw(char *path);
  313. /* Functions */
  314. /*
  315. * CRC8 source:
  316. * https://barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code
  317. */
  318. static void
  319. crc8init()
  320. {
  321. uchar remainder, bit;
  322. uint dividend;
  323. /* Compute the remainder of each possible dividend */
  324. for (dividend = 0; dividend < CRC8_TABLE_LEN; ++dividend) {
  325. /* Start with the dividend followed by zeros */
  326. remainder = dividend << (WIDTH - 8);
  327. /* Perform modulo-2 division, a bit at a time */
  328. for (bit = 8; bit > 0; --bit) {
  329. /* Try to divide the current data bit */
  330. if (remainder & TOPBIT)
  331. remainder = (remainder << 1) ^ POLYNOMIAL;
  332. else
  333. remainder = (remainder << 1);
  334. }
  335. /* Store the result into the table */
  336. crc8table[dividend] = remainder;
  337. }
  338. }
  339. static uchar
  340. crc8fast(uchar const message[], size_t n)
  341. {
  342. static uchar data, remainder;
  343. static size_t byte;
  344. /* Divide the message by the polynomial, a byte at a time */
  345. for (remainder = byte = 0; byte < n; ++byte) {
  346. data = message[byte] ^ (remainder >> (WIDTH - 8));
  347. remainder = crc8table[data] ^ (remainder << 8);
  348. }
  349. /* The final remainder is the CRC */
  350. return remainder;
  351. }
  352. /* Messages show up at the bottom */
  353. static void
  354. printmsg(const char *msg)
  355. {
  356. mvprintw(LINES - 1, 0, "%s\n", msg);
  357. }
  358. /* Kill curses and display error before exiting */
  359. static void
  360. printerr(int linenum)
  361. {
  362. exitcurses();
  363. fprintf(stderr, "line %d: (%d) %s\n", linenum, errno, strerror(errno));
  364. if (cfg.noxdisplay && g_cppath[0])
  365. unlink(g_cppath);
  366. exit(1);
  367. }
  368. /* Print prompt on the last line */
  369. static void
  370. printprompt(char *str)
  371. {
  372. clearprompt();
  373. printw(str);
  374. }
  375. /* Increase the limit on open file descriptors, if possible */
  376. static rlim_t
  377. max_openfds()
  378. {
  379. struct rlimit rl;
  380. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  381. if (limit != 0)
  382. return 32;
  383. limit = rl.rlim_cur;
  384. rl.rlim_cur = rl.rlim_max;
  385. /* Return ~75% of max possible */
  386. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  387. limit = rl.rlim_max - (rl.rlim_max >> 2);
  388. /*
  389. * 20K is arbitrary. If the limit is set to max possible
  390. * value, the memory usage increases to more than double.
  391. */
  392. return limit > 20480 ? 20480 : limit;
  393. }
  394. return limit;
  395. }
  396. /*
  397. * Wrapper to realloc()
  398. * Frees current memory if realloc() fails and returns NULL.
  399. *
  400. * As per the docs, the *alloc() family is supposed to be memory aligned:
  401. * Ubuntu: http://manpages.ubuntu.com/manpages/xenial/man3/malloc.3.html
  402. * OS X: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/malloc.3.html
  403. */
  404. static void *
  405. xrealloc(void *pcur, size_t len)
  406. {
  407. static void *pmem;
  408. pmem = realloc(pcur, len);
  409. if (!pmem && pcur)
  410. free(pcur);
  411. return pmem;
  412. }
  413. /*
  414. * Just a safe strncpy(3)
  415. * Always null ('\0') terminates if both src and dest are valid pointers.
  416. * Returns the number of bytes copied including terminating null byte.
  417. */
  418. static size_t
  419. xstrlcpy(char *dest, const char *src, size_t n)
  420. {
  421. static ulong *s, *d;
  422. static size_t len, blocks;
  423. static const uint lsize = sizeof(ulong);
  424. static const uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
  425. if (!src || !dest || !n)
  426. return 0;
  427. len = strlen(src) + 1;
  428. if (n > len)
  429. n = len;
  430. else if (len > n)
  431. /* Save total number of bytes to copy in len */
  432. len = n;
  433. /*
  434. * To enable -O3 ensure src and dest are 16-byte aligned
  435. * More info: http://www.felixcloutier.com/x86/MOVDQA.html
  436. */
  437. if ((n >= lsize) && (((ulong)src & _ALIGNMENT_MASK) == 0 && ((ulong)dest & _ALIGNMENT_MASK) == 0)) {
  438. s = (ulong *)src;
  439. d = (ulong *)dest;
  440. blocks = n >> _WSHIFT;
  441. n &= lsize - 1;
  442. while (blocks) {
  443. *d = *s;
  444. ++d, ++s;
  445. --blocks;
  446. }
  447. if (!n) {
  448. dest = (char *)d;
  449. *--dest = '\0';
  450. return len;
  451. }
  452. src = (char *)s;
  453. dest = (char *)d;
  454. }
  455. while (--n && (*dest = *src))
  456. ++dest, ++src;
  457. if (!n)
  458. *dest = '\0';
  459. return len;
  460. }
  461. /*
  462. * The poor man's implementation of memrchr(3).
  463. * We are only looking for '/' in this program.
  464. * And we are NOT expecting a '/' at the end.
  465. * Ideally 0 < n <= strlen(s).
  466. */
  467. static void *
  468. xmemrchr(uchar *s, uchar ch, size_t n)
  469. {
  470. static uchar *ptr;
  471. if (!s || !n)
  472. return NULL;
  473. ptr = s + n;
  474. do {
  475. --ptr;
  476. if (*ptr == ch)
  477. return ptr;
  478. } while (s != ptr);
  479. return NULL;
  480. }
  481. /*
  482. * The following dirname(3) implementation does not
  483. * modify the input. We use a copy of the original.
  484. *
  485. * Modified from the glibc (GNU LGPL) version.
  486. */
  487. static char *
  488. xdirname(const char *path)
  489. {
  490. static char * const buf = g_buf, *last_slash, *runp;
  491. xstrlcpy(buf, path, PATH_MAX);
  492. /* Find last '/'. */
  493. last_slash = xmemrchr((uchar *)buf, '/', strlen(buf));
  494. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  495. /* Determine whether all remaining characters are slashes. */
  496. for (runp = last_slash; runp != buf; --runp)
  497. if (runp[-1] != '/')
  498. break;
  499. /* The '/' is the last character, we have to look further. */
  500. if (runp != buf)
  501. last_slash = xmemrchr((uchar *)buf, '/', runp - buf);
  502. }
  503. if (last_slash != NULL) {
  504. /* Determine whether all remaining characters are slashes. */
  505. for (runp = last_slash; runp != buf; --runp)
  506. if (runp[-1] != '/')
  507. break;
  508. /* Terminate the buffer. */
  509. if (runp == buf) {
  510. /* The last slash is the first character in the string.
  511. * We have to return "/". As a special case we have to
  512. * return "//" if there are exactly two slashes at the
  513. * beginning of the string. See XBD 4.10 Path Name
  514. * Resolution for more information.
  515. */
  516. if (last_slash == buf + 1)
  517. ++last_slash;
  518. else
  519. last_slash = buf + 1;
  520. } else
  521. last_slash = runp;
  522. last_slash[0] = '\0';
  523. } else {
  524. /* This assignment is ill-designed but the XPG specs require to
  525. * return a string containing "." in any case no directory part
  526. * is found and so a static and constant string is required.
  527. */
  528. buf[0] = '.';
  529. buf[1] = '\0';
  530. }
  531. return buf;
  532. }
  533. static char *
  534. xbasename(char *path)
  535. {
  536. static char *base;
  537. base = xmemrchr((uchar *)path, '/', strlen(path));
  538. return base ? base + 1 : path;
  539. }
  540. /* Writes buflen char(s) from buf to a file */
  541. static void
  542. writecp(const char *buf, const size_t buflen)
  543. {
  544. if (!g_cppath[0])
  545. return;
  546. FILE *fp = fopen(g_cppath, "w");
  547. if (fp) {
  548. fwrite(buf, 1, buflen, fp);
  549. fclose(fp);
  550. } else
  551. printwarn();
  552. }
  553. static bool
  554. appendfpath(const char *path, const size_t len)
  555. {
  556. if ((copybufpos >= copybuflen) || ((len + 3) > (copybuflen - copybufpos))) {
  557. copybuflen += PATH_MAX;
  558. pcopybuf = xrealloc(pcopybuf, copybuflen);
  559. if (!pcopybuf) {
  560. printmsg("no memory!");
  561. return FALSE;
  562. }
  563. }
  564. if (copybufpos) {
  565. pcopybuf[copybufpos - 1] = '\n';
  566. if (cfg.quote) {
  567. pcopybuf[copybufpos] = '\'';
  568. ++copybufpos;
  569. }
  570. } else if (cfg.quote) {
  571. pcopybuf[copybufpos] = '\'';
  572. ++copybufpos;
  573. }
  574. copybufpos += xstrlcpy(pcopybuf + copybufpos, path, len);
  575. if (cfg.quote) {
  576. pcopybuf[copybufpos - 1] = '\'';
  577. pcopybuf[copybufpos] = '\0';
  578. ++copybufpos;
  579. }
  580. return TRUE;
  581. }
  582. /*
  583. * Return number of dots if all chars in a string are dots, else 0
  584. */
  585. static int
  586. all_dots(const char *path)
  587. {
  588. int count = 0;
  589. if (!path)
  590. return FALSE;
  591. while (*path == '.')
  592. ++count, ++path;
  593. if (*path)
  594. return 0;
  595. return count;
  596. }
  597. /* Initialize curses mode */
  598. static void
  599. initcurses(void)
  600. {
  601. if (initscr() == NULL) {
  602. char *term = getenv("TERM");
  603. if (term != NULL)
  604. fprintf(stderr, "error opening TERM: %s\n", term);
  605. else
  606. fprintf(stderr, "initscr() failed\n");
  607. exit(1);
  608. }
  609. cbreak();
  610. noecho();
  611. nonl();
  612. intrflush(stdscr, FALSE);
  613. keypad(stdscr, TRUE);
  614. curs_set(FALSE); /* Hide cursor */
  615. start_color();
  616. use_default_colors();
  617. if (cfg.showcolor)
  618. init_pair(1, cfg.color, -1);
  619. settimeout(); /* One second */
  620. }
  621. /*
  622. * Spawns a child process. Behaviour can be controlled using flag.
  623. * Limited to 2 arguments to a program, flag works on bit set.
  624. */
  625. static void
  626. spawn(const char *file, const char *arg1, const char *arg2, const char *dir, uchar flag)
  627. {
  628. static char *shlvl;
  629. static pid_t pid;
  630. static int status;
  631. if (flag & F_NORMAL)
  632. exitcurses();
  633. pid = fork();
  634. if (pid == 0) {
  635. if (dir != NULL)
  636. status = chdir(dir);
  637. shlvl = getenv("SHLVL");
  638. /* Show a marker (to indicate nnn spawned shell) */
  639. if (flag & F_MARKER && shlvl != NULL) {
  640. fprintf(stdout, "\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  641. fprintf(stdout, "Next shell level: %d\n", atoi(shlvl) + 1);
  642. }
  643. /* Suppress stdout and stderr */
  644. if (flag & F_NOTRACE) {
  645. int fd = open("/dev/null", O_WRONLY, 0200);
  646. dup2(fd, 1);
  647. dup2(fd, 2);
  648. close(fd);
  649. }
  650. if (flag & F_NOWAIT) {
  651. signal(SIGHUP, SIG_IGN);
  652. signal(SIGPIPE, SIG_IGN);
  653. setsid();
  654. }
  655. if (flag & F_SIGINT)
  656. signal(SIGINT, SIG_DFL);
  657. execlp(file, file, arg1, arg2, NULL);
  658. _exit(1);
  659. } else {
  660. if (!(flag & F_NOWAIT))
  661. /* Ignore interruptions */
  662. while (waitpid(pid, &status, 0) == -1)
  663. DPRINTF_D(status);
  664. DPRINTF_D(pid);
  665. if (flag & F_NORMAL)
  666. refresh();
  667. }
  668. }
  669. /* Get program name from env var, else return fallback program */
  670. static char *
  671. xgetenv(const char *name, char *fallback)
  672. {
  673. static char *value;
  674. if (name == NULL)
  675. return fallback;
  676. value = getenv(name);
  677. return value && value[0] ? value : fallback;
  678. }
  679. /* Check if a dir exists, IS a dir and is readable */
  680. static bool
  681. xdiraccess(const char *path)
  682. {
  683. static DIR *dirp;
  684. dirp = opendir(path);
  685. if (dirp == NULL) {
  686. printwarn();
  687. return FALSE;
  688. }
  689. closedir(dirp);
  690. return TRUE;
  691. }
  692. /*
  693. * We assume none of the strings are NULL.
  694. *
  695. * Let's have the logic to sort numeric names in numeric order.
  696. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  697. *
  698. * If the absolute numeric values are same, we fallback to alphasort.
  699. */
  700. static int
  701. xstricmp(const char * const s1, const char * const s2)
  702. {
  703. static const char *c1, *c2;
  704. c1 = s1;
  705. while (isspace(*c1))
  706. ++c1;
  707. c2 = s2;
  708. while (isspace(*c2))
  709. ++c2;
  710. if (*c1 == '-' || *c1 == '+')
  711. ++c1;
  712. if (*c2 == '-' || *c2 == '+')
  713. ++c2;
  714. if (isdigit(*c1) && isdigit(*c2)) {
  715. while (*c1 >= '0' && *c1 <= '9')
  716. ++c1;
  717. while (isspace(*c1))
  718. ++c1;
  719. while (*c2 >= '0' && *c2 <= '9')
  720. ++c2;
  721. while (isspace(*c2))
  722. ++c2;
  723. }
  724. if (!*c1 && !*c2) {
  725. static long long num1, num2;
  726. num1 = strtoll(s1, NULL, 10);
  727. num2 = strtoll(s2, NULL, 10);
  728. if (num1 != num2) {
  729. if (num1 > num2)
  730. return 1;
  731. else
  732. return -1;
  733. }
  734. }
  735. return strcoll(s1, s2);
  736. }
  737. /* Return the integer value of a char representing HEX */
  738. static char
  739. xchartohex(char c)
  740. {
  741. if (c >= '0' && c <= '9')
  742. return c - '0';
  743. c = TOUPPER(c);
  744. if (c >= 'A' && c <= 'F')
  745. return c - 'A' + 10;
  746. return c;
  747. }
  748. static char *
  749. getmime(const char *file)
  750. {
  751. static regex_t regex;
  752. static uint i;
  753. static const uint len = LEN(assocs);
  754. for (i = 0; i < len; ++i) {
  755. if (regcomp(&regex, assocs[i].regex, REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  756. continue;
  757. if (regexec(&regex, file, 0, NULL, 0) == 0) {
  758. regfree(&regex);
  759. return assocs[i].mime;
  760. }
  761. }
  762. regfree(&regex);
  763. return NULL;
  764. }
  765. static int
  766. setfilter(regex_t *regex, char *filter)
  767. {
  768. static size_t len;
  769. static int r;
  770. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  771. if (r != 0 && filter && filter[0] != '\0') {
  772. len = COLS;
  773. if (len > NAME_MAX)
  774. len = NAME_MAX;
  775. regerror(r, regex, g_buf, len);
  776. printmsg(g_buf);
  777. }
  778. return r;
  779. }
  780. static void
  781. initfilter(int dot, char **ifilter)
  782. {
  783. *ifilter = dot ? "." : "^[^.]";
  784. }
  785. static int
  786. visible(regex_t *regex, char *file)
  787. {
  788. return regexec(regex, file, 0, NULL, 0) == 0;
  789. }
  790. static int
  791. entrycmp(const void *va, const void *vb)
  792. {
  793. static pEntry pa, pb;
  794. pa = (pEntry)va;
  795. pb = (pEntry)vb;
  796. /* Sort directories first */
  797. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  798. return 1;
  799. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  800. return -1;
  801. /* Do the actual sorting */
  802. if (cfg.mtimeorder)
  803. return pb->t - pa->t;
  804. if (cfg.sizeorder) {
  805. if (pb->size > pa->size)
  806. return 1;
  807. else if (pb->size < pa->size)
  808. return -1;
  809. }
  810. if (cfg.blkorder) {
  811. if (pb->blocks > pa->blocks)
  812. return 1;
  813. else if (pb->blocks < pa->blocks)
  814. return -1;
  815. }
  816. return xstricmp(pa->name, pb->name);
  817. }
  818. /*
  819. * Returns SEL_* if key is bound and 0 otherwise.
  820. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  821. * The next keyboard input can be simulated by presel.
  822. */
  823. static int
  824. nextsel(char **run, char **env, int *presel)
  825. {
  826. static int c;
  827. static uint i;
  828. static const uint len = LEN(bindings);
  829. #ifdef LINUX_INOTIFY
  830. static char inotify_buf[EVENT_BUF_LEN];
  831. #elif defined(BSD_KQUEUE)
  832. static struct kevent event_data[NUM_EVENT_SLOTS];
  833. #endif
  834. c = *presel;
  835. if (c == 0)
  836. c = getch();
  837. else {
  838. *presel = 0;
  839. /* Unwatch dir if we are still in a filtered view */
  840. #ifdef LINUX_INOTIFY
  841. if (inotify_wd >= 0) {
  842. inotify_rm_watch(inotify_fd, inotify_wd);
  843. inotify_wd = -1;
  844. }
  845. #elif defined(BSD_KQUEUE)
  846. if (event_fd >= 0) {
  847. close(event_fd);
  848. event_fd = -1;
  849. }
  850. #endif
  851. }
  852. if (c == -1) {
  853. ++idle;
  854. /* Do not check for directory changes in du
  855. * mode. A redraw forces du calculation.
  856. * Check for changes every odd second.
  857. */
  858. #ifdef LINUX_INOTIFY
  859. if (!cfg.blkorder && inotify_wd >= 0 && idle & 1 && read(inotify_fd, inotify_buf, EVENT_BUF_LEN) > 0)
  860. #elif defined(BSD_KQUEUE)
  861. if (!cfg.blkorder && event_fd >= 0 && idle & 1
  862. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS, event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  863. #endif
  864. c = CONTROL('L');
  865. } else
  866. idle = 0;
  867. for (i = 0; i < len; ++i)
  868. if (c == bindings[i].sym) {
  869. *run = bindings[i].run;
  870. *env = bindings[i].env;
  871. return bindings[i].act;
  872. }
  873. return 0;
  874. }
  875. /*
  876. * Move non-matching entries to the end
  877. */
  878. static int
  879. fill(struct entry **dents, int (*filter)(regex_t *, char *), regex_t *re)
  880. {
  881. static int count;
  882. static struct entry _dent, *pdent1, *pdent2;
  883. for (count = 0; count < ndents; ++count) {
  884. if (filter(re, (*dents)[count].name) == 0) {
  885. if (count != --ndents) {
  886. pdent1 = &(*dents)[count];
  887. pdent2 = &(*dents)[ndents];
  888. *(&_dent) = *pdent1;
  889. *pdent1 = *pdent2;
  890. *pdent2 = *(&_dent);
  891. --count;
  892. }
  893. continue;
  894. }
  895. }
  896. return ndents;
  897. }
  898. static int
  899. matches(char *fltr)
  900. {
  901. static regex_t re;
  902. /* Search filter */
  903. if (setfilter(&re, fltr) != 0)
  904. return -1;
  905. ndents = fill(&dents, visible, &re);
  906. regfree(&re);
  907. if (!ndents)
  908. return 0;
  909. qsort(dents, ndents, sizeof(*dents), entrycmp);
  910. return 0;
  911. }
  912. static int
  913. filterentries(char *path)
  914. {
  915. static char ln[REGEX_MAX] __attribute__ ((aligned));
  916. static wchar_t wln[REGEX_MAX] __attribute__ ((aligned));
  917. static wint_t ch[2] = {0};
  918. int r, total = ndents, oldcur = cur, len = 1;
  919. char *pln = ln + 1;
  920. ln[0] = wln[0] = FILTER;
  921. ln[1] = wln[1] = '\0';
  922. cur = 0;
  923. cleartimeout();
  924. echo();
  925. curs_set(TRUE);
  926. printprompt(ln);
  927. while ((r = get_wch(ch)) != ERR) {
  928. if (*ch == 127 /* handle DEL */ || *ch == KEY_DC || *ch == KEY_BACKSPACE || *ch == '\b') {
  929. if (len == 1) {
  930. cur = oldcur;
  931. *ch = CONTROL('L');
  932. goto end;
  933. }
  934. wln[--len] = '\0';
  935. if (len == 1)
  936. cur = oldcur;
  937. wcstombs(ln, wln, REGEX_MAX);
  938. ndents = total;
  939. if (matches(pln) != -1)
  940. redraw(path);
  941. printprompt(ln);
  942. continue;
  943. }
  944. if (r == OK) {
  945. /* Handle all control chars in main loop */
  946. if (keyname(*ch)[0] == '^') {
  947. if (len == 1)
  948. cur = oldcur;
  949. goto end;
  950. }
  951. switch (*ch) {
  952. case '\r': // with nonl(), this is ENTER key value
  953. if (len == 1) {
  954. cur = oldcur;
  955. goto end;
  956. }
  957. if (matches(pln) == -1)
  958. goto end;
  959. redraw(path);
  960. goto end;
  961. case '?': // '?' is an invalid regex, show help instead
  962. if (len == 1) {
  963. cur = oldcur;
  964. goto end;
  965. } // fallthrough
  966. default:
  967. /* Reset cur in case it's a repeat search */
  968. if (len == 1)
  969. cur = 0;
  970. if (len == REGEX_MAX - 1)
  971. break;
  972. wln[len] = (wchar_t)*ch;
  973. wln[++len] = '\0';
  974. wcstombs(ln, wln, REGEX_MAX);
  975. /* Forward-filtering optimization:
  976. * - new matches can only be a subset of current matches.
  977. */
  978. /* ndents = total; */
  979. if (matches(pln) == -1)
  980. continue;
  981. /* If the only match is a dir, auto-select and cd into it */
  982. if (cfg.filtermode && ndents == 1 && S_ISDIR(dents[0].mode)) {
  983. *ch = KEY_ENTER;
  984. cur = 0;
  985. goto end;
  986. }
  987. /*
  988. * redraw() should be above the auto-select optimization, for
  989. * the case where there's an issue with dir auto-select, say,
  990. * due to a permission problem. The transition is jumpy in
  991. * case of such an error. However, we optimize for successful
  992. * cases where the dir has permissions. This skips a redraw().
  993. */
  994. redraw(path);
  995. printprompt(ln);
  996. }
  997. } else {
  998. if (len == 1)
  999. cur = oldcur;
  1000. goto end;
  1001. }
  1002. }
  1003. end:
  1004. noecho();
  1005. curs_set(FALSE);
  1006. settimeout();
  1007. /* Return keys for navigation etc. */
  1008. return *ch;
  1009. }
  1010. /* Show a prompt with input string and return the changes */
  1011. static char *
  1012. xreadline(char *fname, char *prompt)
  1013. {
  1014. int old_curs = curs_set(1);
  1015. size_t len, pos;
  1016. int x, y, r;
  1017. wint_t ch[2] = {0};
  1018. static wchar_t * const buf = (wchar_t *)g_buf;
  1019. printprompt(prompt);
  1020. if (fname) {
  1021. DPRINTF_S(fname);
  1022. len = pos = mbstowcs(buf, fname, NAME_MAX);
  1023. } else
  1024. len = (size_t)-1;
  1025. if (len == (size_t)-1) {
  1026. buf[0] = '\0';
  1027. len = pos = 0;
  1028. }
  1029. getyx(stdscr, y, x);
  1030. cleartimeout();
  1031. while (1) {
  1032. buf[len] = ' ';
  1033. mvaddnwstr(y, x, buf, len + 1);
  1034. move(y, x + wcswidth(buf, pos));
  1035. r = get_wch(ch);
  1036. if (r != ERR) {
  1037. if (r == OK) {
  1038. switch (*ch) {
  1039. case KEY_ENTER: //fallthrough
  1040. case '\n': //fallthrough
  1041. case '\r':
  1042. goto END;
  1043. case '\b': /* some old curses (e.g. rhel25) still send '\b' for backspace */
  1044. if (pos > 0) {
  1045. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1046. --len, --pos;
  1047. } //fallthrough
  1048. case '\t': /* TAB breaks cursor position, ignore it */
  1049. continue;
  1050. case CONTROL('L'):
  1051. clearprompt();
  1052. printprompt(prompt);
  1053. len = pos = 0;
  1054. continue;
  1055. case CONTROL('A'):
  1056. pos = 0;
  1057. continue;
  1058. case CONTROL('E'):
  1059. pos = len;
  1060. continue;
  1061. case CONTROL('U'):
  1062. clearprompt();
  1063. printprompt(prompt);
  1064. memmove(buf, buf + pos, (len - pos) << 2);
  1065. len -= pos;
  1066. pos = 0;
  1067. continue;
  1068. }
  1069. /* Filter out all other control chars */
  1070. if (keyname(*ch)[0] == '^')
  1071. continue;
  1072. if (pos < NAME_MAX - 1) {
  1073. memmove(buf + pos + 1, buf + pos, (len - pos) << 2);
  1074. buf[pos] = *ch;
  1075. ++len, ++pos;
  1076. continue;
  1077. }
  1078. } else {
  1079. switch (*ch) {
  1080. case KEY_LEFT:
  1081. if (pos > 0)
  1082. --pos;
  1083. break;
  1084. case KEY_RIGHT:
  1085. if (pos < len)
  1086. ++pos;
  1087. break;
  1088. case KEY_BACKSPACE:
  1089. if (pos > 0) {
  1090. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1091. --len, --pos;
  1092. }
  1093. break;
  1094. case KEY_DC:
  1095. if (pos < len) {
  1096. memmove(buf + pos, buf + pos + 1, (len - pos - 1) << 2);
  1097. --len;
  1098. }
  1099. break;
  1100. default:
  1101. break;
  1102. }
  1103. }
  1104. }
  1105. }
  1106. END:
  1107. buf[len] = '\0';
  1108. if (old_curs != ERR)
  1109. curs_set(old_curs);
  1110. settimeout();
  1111. DPRINTF_S(buf);
  1112. wcstombs(g_buf, buf, NAME_MAX);
  1113. clearprompt();
  1114. return g_buf;
  1115. }
  1116. /*
  1117. * Updates out with "dir/name or "/name"
  1118. * Returns the number of bytes copied including the terminating NULL byte
  1119. */
  1120. static size_t
  1121. mkpath(char *dir, char *name, char *out, size_t n)
  1122. {
  1123. static size_t len;
  1124. /* Handle absolute path */
  1125. if (name[0] == '/')
  1126. return xstrlcpy(out, name, n);
  1127. /* Handle root case */
  1128. if (istopdir(dir))
  1129. len = 1;
  1130. else
  1131. len = xstrlcpy(out, dir, n);
  1132. out[len - 1] = '/';
  1133. return (xstrlcpy(out + len, name, n - len) + len);
  1134. }
  1135. static void
  1136. parsebmstr()
  1137. {
  1138. int i = 0;
  1139. char *bms = getenv("NNN_BMS");
  1140. if (!bms)
  1141. return;
  1142. while (*bms && i < BM_MAX) {
  1143. bookmark[i].key = bms;
  1144. ++bms;
  1145. while (*bms && *bms != ':')
  1146. ++bms;
  1147. if (!*bms) {
  1148. bookmark[i].key = NULL;
  1149. break;
  1150. }
  1151. *bms = '\0';
  1152. bookmark[i].loc = ++bms;
  1153. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  1154. bookmark[i].key = NULL;
  1155. break;
  1156. }
  1157. while (*bms && *bms != ';')
  1158. ++bms;
  1159. if (*bms)
  1160. *bms = '\0';
  1161. else
  1162. break;
  1163. ++bms;
  1164. ++i;
  1165. }
  1166. }
  1167. /*
  1168. * Get the real path to a bookmark
  1169. *
  1170. * NULL is returned in case of no match, path resolution failure etc.
  1171. * buf would be modified, so check return value before access
  1172. */
  1173. static char *
  1174. get_bm_loc(char *key, char *buf)
  1175. {
  1176. int r;
  1177. if (!key || !key[0])
  1178. return NULL;
  1179. for (r = 0; bookmark[r].key && r < BM_MAX; ++r) {
  1180. if (strcmp(bookmark[r].key, key) == 0) {
  1181. if (bookmark[r].loc[0] == '~') {
  1182. char *home = getenv("HOME");
  1183. if (!home) {
  1184. DPRINTF_S(messages[STR_NOHOME_ID]);
  1185. return NULL;
  1186. }
  1187. snprintf(buf, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  1188. } else
  1189. xstrlcpy(buf, bookmark[r].loc, PATH_MAX);
  1190. return buf;
  1191. }
  1192. }
  1193. DPRINTF_S("Invalid key");
  1194. return NULL;
  1195. }
  1196. static void
  1197. resetdircolor(mode_t mode)
  1198. {
  1199. if (cfg.dircolor && !S_ISDIR(mode)) {
  1200. attroff(COLOR_PAIR(1) | A_BOLD);
  1201. cfg.dircolor = 0;
  1202. }
  1203. }
  1204. /*
  1205. * Replace escape characters in a string with '?'
  1206. * Adjust string length to maxcols if > 0;
  1207. *
  1208. * Interestingly, note that unescape() uses g_buf. What happens if
  1209. * str also points to g_buf? In this case we assume that the caller
  1210. * acknowledges that it's OK to lose the data in g_buf after this
  1211. * call to unescape().
  1212. * The API, on its part, first converts str to multibyte (after which
  1213. * it doesn't touch str anymore). Only after that it starts modifying
  1214. * g_buf. This is a phased operation.
  1215. */
  1216. static char *
  1217. unescape(const char *str, uint maxcols)
  1218. {
  1219. static wchar_t wbuf[PATH_MAX] __attribute__ ((aligned));
  1220. static wchar_t *buf;
  1221. static size_t len;
  1222. /* Convert multi-byte to wide char */
  1223. len = mbstowcs(wbuf, str, PATH_MAX);
  1224. g_buf[0] = '\0';
  1225. buf = wbuf;
  1226. if (maxcols && len > maxcols) {
  1227. len = wcswidth(wbuf, len);
  1228. if (len > maxcols)
  1229. wbuf[maxcols] = 0;
  1230. }
  1231. while (*buf) {
  1232. if (*buf <= '\x1f' || *buf == '\x7f')
  1233. *buf = '\?';
  1234. ++buf;
  1235. }
  1236. /* Convert wide char to multi-byte */
  1237. wcstombs(g_buf, wbuf, PATH_MAX);
  1238. return g_buf;
  1239. }
  1240. static char *
  1241. coolsize(off_t size)
  1242. {
  1243. static const char * const U = "BKMGTPEZY";
  1244. static char size_buf[12]; /* Buffer to hold human readable size */
  1245. static off_t rem;
  1246. static int i;
  1247. i = 0;
  1248. rem = 0;
  1249. while (size > 1024) {
  1250. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  1251. size >>= 10;
  1252. ++i;
  1253. }
  1254. if (i == 1) {
  1255. rem = (rem * 1000) >> 10;
  1256. rem /= 10;
  1257. if (rem % 10 >= 5) {
  1258. rem = (rem / 10) + 1;
  1259. if (rem == 10) {
  1260. ++size;
  1261. rem = 0;
  1262. }
  1263. } else
  1264. rem /= 10;
  1265. } else if (i == 2) {
  1266. rem = (rem * 1000) >> 10;
  1267. if (rem % 10 >= 5) {
  1268. rem = (rem / 10) + 1;
  1269. if (rem == 100) {
  1270. ++size;
  1271. rem = 0;
  1272. }
  1273. } else
  1274. rem /= 10;
  1275. } else if (i > 0) {
  1276. rem = (rem * 10000) >> 10;
  1277. if (rem % 10 >= 5) {
  1278. rem = (rem / 10) + 1;
  1279. if (rem == 1000) {
  1280. ++size;
  1281. rem = 0;
  1282. }
  1283. } else
  1284. rem /= 10;
  1285. }
  1286. if (i > 0)
  1287. snprintf(size_buf, 12, "%lu.%0*lu%c", (ulong)size, i, (ulong)rem, U[i]);
  1288. else
  1289. snprintf(size_buf, 12, "%lu%c", (ulong)size, U[i]);
  1290. return size_buf;
  1291. }
  1292. static char *
  1293. get_file_sym(mode_t mode)
  1294. {
  1295. static char ind[2] = "\0\0";
  1296. if (S_ISDIR(mode))
  1297. ind[0] = '/';
  1298. else if (S_ISLNK(mode))
  1299. ind[0] = '@';
  1300. else if (S_ISSOCK(mode))
  1301. ind[0] = '=';
  1302. else if (S_ISFIFO(mode))
  1303. ind[0] = '|';
  1304. else if (mode & 0100)
  1305. ind[0] = '*';
  1306. else
  1307. ind[0] = '\0';
  1308. return ind;
  1309. }
  1310. static void
  1311. printent(struct entry *ent, int sel, uint namecols)
  1312. {
  1313. static char *pname;
  1314. pname = unescape(ent->name, namecols);
  1315. /* Directories are always shown on top */
  1316. resetdircolor(ent->mode);
  1317. printw("%s%s%s\n", CURSYM(sel), pname, get_file_sym(ent->mode));
  1318. }
  1319. static void
  1320. printent_long(struct entry *ent, int sel, uint namecols)
  1321. {
  1322. static char buf[18], *pname;
  1323. strftime(buf, 18, "%F %R", localtime(&ent->t));
  1324. pname = unescape(ent->name, namecols);
  1325. /* Directories are always shown on top */
  1326. resetdircolor(ent->mode);
  1327. if (sel)
  1328. attron(A_REVERSE);
  1329. if (S_ISDIR(ent->mode)) {
  1330. if (cfg.blkorder)
  1331. printw("%s%-16.16s %8.8s/ %s/\n", CURSYM(sel), buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1332. else
  1333. printw("%s%-16.16s / %s/\n", CURSYM(sel), buf, pname);
  1334. } else if (S_ISLNK(ent->mode)) {
  1335. if (ent->flags & SYMLINK_TO_DIR)
  1336. printw("%s%-16.16s @/ %s@\n", CURSYM(sel), buf, pname);
  1337. else
  1338. printw("%s%-16.16s @ %s@\n", CURSYM(sel), buf, pname);
  1339. } else if (S_ISSOCK(ent->mode))
  1340. printw("%s%-16.16s = %s=\n", CURSYM(sel), buf, pname);
  1341. else if (S_ISFIFO(ent->mode))
  1342. printw("%s%-16.16s | %s|\n", CURSYM(sel), buf, pname);
  1343. else if (S_ISBLK(ent->mode))
  1344. printw("%s%-16.16s b %s\n", CURSYM(sel), buf, pname);
  1345. else if (S_ISCHR(ent->mode))
  1346. printw("%s%-16.16s c %s\n", CURSYM(sel), buf, pname);
  1347. else if (ent->mode & 0100) {
  1348. if (cfg.blkorder)
  1349. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1350. else
  1351. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1352. } else {
  1353. if (cfg.blkorder)
  1354. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1355. else
  1356. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1357. }
  1358. if (sel)
  1359. attroff(A_REVERSE);
  1360. }
  1361. static void (*printptr)(struct entry *ent, int sel, uint namecols) = &printent_long;
  1362. static char
  1363. get_fileind(mode_t mode, char *desc)
  1364. {
  1365. static char c;
  1366. if (S_ISREG(mode)) {
  1367. c = '-';
  1368. xstrlcpy(desc, "regular file", DESCRIPTOR_LEN);
  1369. if (mode & 0100)
  1370. xstrlcpy(desc + 12, ", executable", DESCRIPTOR_LEN - 12); /* Length of string "regular file" is 12 */
  1371. } else if (S_ISDIR(mode)) {
  1372. c = 'd';
  1373. xstrlcpy(desc, "directory", DESCRIPTOR_LEN);
  1374. } else if (S_ISBLK(mode)) {
  1375. c = 'b';
  1376. xstrlcpy(desc, "block special device", DESCRIPTOR_LEN);
  1377. } else if (S_ISCHR(mode)) {
  1378. c = 'c';
  1379. xstrlcpy(desc, "character special device", DESCRIPTOR_LEN);
  1380. #ifdef S_ISFIFO
  1381. } else if (S_ISFIFO(mode)) {
  1382. c = 'p';
  1383. xstrlcpy(desc, "FIFO", DESCRIPTOR_LEN);
  1384. #endif /* S_ISFIFO */
  1385. #ifdef S_ISLNK
  1386. } else if (S_ISLNK(mode)) {
  1387. c = 'l';
  1388. xstrlcpy(desc, "symbolic link", DESCRIPTOR_LEN);
  1389. #endif /* S_ISLNK */
  1390. #ifdef S_ISSOCK
  1391. } else if (S_ISSOCK(mode)) {
  1392. c = 's';
  1393. xstrlcpy(desc, "socket", DESCRIPTOR_LEN);
  1394. #endif /* S_ISSOCK */
  1395. #ifdef S_ISDOOR
  1396. /* Solaris 2.6, etc. */
  1397. } else if (S_ISDOOR(mode)) {
  1398. c = 'D';
  1399. desc[0] = '\0';
  1400. #endif /* S_ISDOOR */
  1401. } else {
  1402. /* Unknown type -- possibly a regular file? */
  1403. c = '?';
  1404. desc[0] = '\0';
  1405. }
  1406. return c;
  1407. }
  1408. /* Convert a mode field into "ls -l" type perms field. */
  1409. static char *
  1410. get_lsperms(mode_t mode, char *desc)
  1411. {
  1412. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1413. static char bits[11] = {'\0'};
  1414. bits[0] = get_fileind(mode, desc);
  1415. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  1416. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  1417. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  1418. if (mode & S_ISUID)
  1419. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1420. if (mode & S_ISGID)
  1421. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1422. if (mode & S_ISVTX)
  1423. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1424. return bits;
  1425. }
  1426. /*
  1427. * Gets only a single line (that's what we need
  1428. * for now) or shows full command output in pager.
  1429. *
  1430. * If pager is valid, returns NULL
  1431. */
  1432. static char *
  1433. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager)
  1434. {
  1435. pid_t pid;
  1436. int pipefd[2];
  1437. FILE *pf;
  1438. int tmp, flags;
  1439. char *ret = NULL;
  1440. if (pipe(pipefd) == -1)
  1441. errexit();
  1442. for (tmp = 0; tmp < 2; ++tmp) {
  1443. /* Get previous flags */
  1444. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1445. /* Set bit for non-blocking flag */
  1446. flags |= O_NONBLOCK;
  1447. /* Change flags on fd */
  1448. fcntl(pipefd[tmp], F_SETFL, flags);
  1449. }
  1450. pid = fork();
  1451. if (pid == 0) {
  1452. /* In child */
  1453. close(pipefd[0]);
  1454. dup2(pipefd[1], STDOUT_FILENO);
  1455. dup2(pipefd[1], STDERR_FILENO);
  1456. close(pipefd[1]);
  1457. execlp(file, file, arg1, arg2, NULL);
  1458. _exit(1);
  1459. }
  1460. /* In parent */
  1461. waitpid(pid, &tmp, 0);
  1462. close(pipefd[1]);
  1463. if (!pager) {
  1464. pf = fdopen(pipefd[0], "r");
  1465. if (pf) {
  1466. ret = fgets(buf, bytes, pf);
  1467. close(pipefd[0]);
  1468. }
  1469. return ret;
  1470. }
  1471. pid = fork();
  1472. if (pid == 0) {
  1473. /* Show in pager in child */
  1474. dup2(pipefd[0], STDIN_FILENO);
  1475. close(pipefd[0]);
  1476. execlp("less", "less", NULL);
  1477. _exit(1);
  1478. }
  1479. /* In parent */
  1480. waitpid(pid, &tmp, 0);
  1481. close(pipefd[0]);
  1482. return NULL;
  1483. }
  1484. static char *
  1485. xgetpwuid(uid_t uid)
  1486. {
  1487. struct passwd *pwd = getpwuid(uid);
  1488. if (!pwd)
  1489. return utils[UNKNOWN];
  1490. return pwd->pw_name;
  1491. }
  1492. static char *
  1493. xgetgrgid(gid_t gid)
  1494. {
  1495. struct group *grp = getgrgid(gid);
  1496. if (!grp)
  1497. return utils[UNKNOWN];
  1498. return grp->gr_name;
  1499. }
  1500. /*
  1501. * Follows the stat(1) output closely
  1502. */
  1503. static int
  1504. show_stats(char *fpath, char *fname, struct stat *sb)
  1505. {
  1506. char desc[DESCRIPTOR_LEN];
  1507. char *perms = get_lsperms(sb->st_mode, desc);
  1508. char *p, *begin = g_buf;
  1509. if (g_homepath[0])
  1510. xstrlcpy(g_homepath + g_homelen - 1, "/.nnnXXXXXX", MAX_HOME_LEN - g_homelen);
  1511. else {
  1512. printmsg(messages[STR_NOHOME_ID]);
  1513. return -1;
  1514. }
  1515. int fd = mkstemp(g_homepath);
  1516. if (fd == -1)
  1517. return -1;
  1518. dprintf(fd, " File: '%s'", unescape(fname, 0));
  1519. /* Show file name or 'symlink' -> 'target' */
  1520. if (perms[0] == 'l') {
  1521. /* Note that MAX_CMD_LEN > PATH_MAX */
  1522. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1523. if (len != -1) {
  1524. struct stat tgtsb;
  1525. if (!stat(fpath, &tgtsb) && S_ISDIR(tgtsb.st_mode))
  1526. g_buf[len++] = '/';
  1527. g_buf[len] = '\0';
  1528. /*
  1529. * We pass g_buf but unescape() operates on g_buf too!
  1530. * Read the API notes for information on how this works.
  1531. */
  1532. dprintf(fd, " -> '%s'", unescape(g_buf, 0));
  1533. }
  1534. }
  1535. /* Show size, blocks, file type */
  1536. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1537. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1538. (long long)sb->st_size, (long long)sb->st_blocks, sb->st_blksize, desc);
  1539. #else
  1540. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1541. sb->st_size, sb->st_blocks, (long)sb->st_blksize, desc);
  1542. #endif
  1543. /* Show containing device, inode, hardlink count */
  1544. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1545. snprintf(g_buf, 32, "%xh/%ud", sb->st_dev, sb->st_dev);
  1546. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1547. g_buf, (unsigned long long)sb->st_ino, sb->st_nlink);
  1548. #else
  1549. snprintf(g_buf, 32, "%lxh/%lud", (ulong)sb->st_dev, (ulong)sb->st_dev);
  1550. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1551. g_buf, sb->st_ino, (ulong)sb->st_nlink);
  1552. #endif
  1553. /* Show major, minor number for block or char device */
  1554. if (perms[0] == 'b' || perms[0] == 'c')
  1555. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1556. /* Show permissions, owner, group */
  1557. 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,
  1558. sb->st_mode & 7, perms, sb->st_uid, xgetpwuid(sb->st_uid), sb->st_gid, xgetgrgid(sb->st_gid));
  1559. /* Show last access time */
  1560. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_atime));
  1561. dprintf(fd, "\n\n Access: %s", g_buf);
  1562. /* Show last modification time */
  1563. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_mtime));
  1564. dprintf(fd, "\n Modify: %s", g_buf);
  1565. /* Show last status change time */
  1566. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_ctime));
  1567. dprintf(fd, "\n Change: %s", g_buf);
  1568. if (S_ISREG(sb->st_mode)) {
  1569. /* Show file(1) output */
  1570. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1571. if (p) {
  1572. dprintf(fd, "\n\n ");
  1573. while (*p) {
  1574. if (*p == ',') {
  1575. *p = '\0';
  1576. dprintf(fd, " %s\n", begin);
  1577. begin = p + 1;
  1578. }
  1579. ++p;
  1580. }
  1581. dprintf(fd, " %s", begin);
  1582. }
  1583. dprintf(fd, "\n\n");
  1584. } else
  1585. dprintf(fd, "\n\n\n");
  1586. close(fd);
  1587. exitcurses();
  1588. get_output(NULL, 0, "cat", g_homepath, NULL, 1);
  1589. unlink(g_homepath);
  1590. refresh();
  1591. return 0;
  1592. }
  1593. static size_t
  1594. get_fs_info(const char *path, bool type)
  1595. {
  1596. static struct statvfs svb;
  1597. if (statvfs(path, &svb) == -1)
  1598. return 0;
  1599. if (type == CAPACITY)
  1600. return svb.f_blocks << ffs(svb.f_bsize >> 1);
  1601. else
  1602. return svb.f_bavail << ffs(svb.f_frsize >> 1);
  1603. }
  1604. static int
  1605. show_mediainfo(char *fpath, char *arg)
  1606. {
  1607. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[cfg.metaviewer], NULL, 0))
  1608. return -1;
  1609. exitcurses();
  1610. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, 1);
  1611. refresh();
  1612. return 0;
  1613. }
  1614. static int
  1615. handle_archive(char *fpath, char *arg, char *dir)
  1616. {
  1617. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[ATOOL], NULL, 0))
  1618. return -1;
  1619. if (arg[1] == 'x')
  1620. spawn(utils[ATOOL], arg, fpath, dir, F_NORMAL);
  1621. else {
  1622. exitcurses();
  1623. get_output(NULL, 0, utils[ATOOL], arg, fpath, 1);
  1624. refresh();
  1625. }
  1626. return 0;
  1627. }
  1628. /*
  1629. * The help string tokens (each line) start with a HEX value
  1630. * which indicates the number of spaces to print before the
  1631. * particular token. This method was chosen instead of a flat
  1632. * string because the number of bytes in help was increasing
  1633. * the binary size by around a hundred bytes. This would only
  1634. * have increased as we keep adding new options.
  1635. */
  1636. static int
  1637. show_help(char *path)
  1638. {
  1639. if (g_homepath[0])
  1640. xstrlcpy(g_homepath + g_homelen - 1, "/.nnnXXXXXX", MAX_HOME_LEN - g_homelen);
  1641. else {
  1642. printmsg(messages[STR_NOHOME_ID]);
  1643. return -1;
  1644. }
  1645. int i = 0, fd = mkstemp(g_homepath);
  1646. char *start, *end;
  1647. static char helpstr[] = {
  1648. "cKey Desc\n"
  1649. "e----\n"
  1650. "7↑, k, ^P Prev entry\n"
  1651. "7↓, j, ^N Next entry\n"
  1652. "7PgUp, ^U Scroll half page up\n"
  1653. "7PgDn, ^D Scroll half page down\n"
  1654. "1Home, g, ^, ^A First entry\n"
  1655. "2End, G, $, ^E Last entry\n"
  1656. "4→, ↵, l, ^M Open file/enter dir\n"
  1657. "1←, Bksp, h, ^H Parent dir\n"
  1658. "d^O Open with...\n"
  1659. "5Insert, ^I Toggle nav-as-you-type\n"
  1660. "e~ Go HOME\n"
  1661. "e& Start-up dir\n"
  1662. "e- Last visited dir\n"
  1663. "e/ Filter entries\n"
  1664. "d^/ Open desktop search app\n"
  1665. "e. Toggle show . files\n"
  1666. "d^B Bookmark prompt\n"
  1667. "eb Pin current dir\n"
  1668. "d^V Go to pinned dir\n"
  1669. "ec Change dir prompt\n"
  1670. "ed Toggle detail view\n"
  1671. "eD File details\n"
  1672. "em Brief media info\n"
  1673. "eM Full media info\n"
  1674. "en Create new\n"
  1675. "d^R Rename entry\n"
  1676. "er Open dir in vidir\n"
  1677. "es Toggle sort by size\n"
  1678. "eS Toggle apparent size\n"
  1679. "d^J Toggle du mode\n"
  1680. "et Toggle sort by mtime\n"
  1681. "a!, ^] Spawn SHELL in dir\n"
  1682. "eR Run custom script\n"
  1683. "ee Edit entry in EDITOR\n"
  1684. "eo Open DE filemanager\n"
  1685. "ep Open entry in PAGER\n"
  1686. "ef Archive entry\n"
  1687. "eF List archive\n"
  1688. "d^F Extract archive\n"
  1689. "6Space, ^K Copy file path\n"
  1690. "d^Y Toggle multi-copy\n"
  1691. "d^T Toggle path quote\n"
  1692. "d^L Redraw, clear prompt\n"
  1693. "eL Lock terminal\n"
  1694. "e? Help, settings\n"
  1695. "aQ, ^G Quit and cd\n"
  1696. "aq, ^X Quit\n\n"};
  1697. if (fd == -1)
  1698. return -1;
  1699. start = end = helpstr;
  1700. while (*end) {
  1701. while (*end != '\n')
  1702. ++end;
  1703. if (start == end) {
  1704. ++end;
  1705. continue;
  1706. }
  1707. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1708. start = ++end;
  1709. }
  1710. dprintf(fd, "\nVolume: %s of ", coolsize(get_fs_info(path, FREE)));
  1711. dprintf(fd, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  1712. if (getenv("NNN_BMS")) {
  1713. dprintf(fd, "BOOKMARKS\n");
  1714. for (; i < BM_MAX; ++i)
  1715. if (bookmark[i].key)
  1716. dprintf(fd, " %s: %s\n", bookmark[i].key, bookmark[i].loc);
  1717. else
  1718. break;
  1719. dprintf(fd, "\n");
  1720. }
  1721. if (editor)
  1722. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1723. if (dmanager)
  1724. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", dmanager);
  1725. if (idletimeout)
  1726. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1727. if (copier)
  1728. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1729. if (getenv("NNN_NO_X"))
  1730. dprintf(fd, "NNN_NO_X: %s (%s)\n", getenv("NNN_NO_X"), g_cppath);
  1731. if (getenv("NNN_SCRIPT"))
  1732. dprintf(fd, "NNN_SCRIPT: %s\n", getenv("NNN_SCRIPT"));
  1733. if (getenv("NNN_MULTISCRIPT"))
  1734. dprintf(fd, "NNN_MULTISCRIPT: %s\n", getenv("NNN_MULTISCRIPT"));
  1735. if (getenv("NNN_SHOW_HIDDEN"))
  1736. dprintf(fd, "NNN_SHOW_HIDDEN: %s\n", getenv("NNN_SHOW_HIDDEN"));
  1737. dprintf(fd, "\n");
  1738. if (getenv("PWD"))
  1739. dprintf(fd, "PWD: %s\n", getenv("PWD"));
  1740. if (getenv("SHELL"))
  1741. dprintf(fd, "SHELL: %s\n", getenv("SHELL"));
  1742. if (getenv("SHLVL"))
  1743. dprintf(fd, "SHLVL: %s\n", getenv("SHLVL"));
  1744. if (getenv("VISUAL"))
  1745. dprintf(fd, "VISUAL: %s\n", getenv("VISUAL"));
  1746. else if (getenv("EDITOR"))
  1747. dprintf(fd, "EDITOR: %s\n", getenv("EDITOR"));
  1748. if (getenv("PAGER"))
  1749. dprintf(fd, "PAGER: %s\n", getenv("PAGER"));
  1750. dprintf(fd, "\nVersion: %s\n%s\n", VERSION, GENERAL_INFO);
  1751. close(fd);
  1752. exitcurses();
  1753. get_output(NULL, 0, "cat", g_homepath, NULL, 1);
  1754. unlink(g_homepath);
  1755. refresh();
  1756. return 0;
  1757. }
  1758. int (*nftw_fn) (const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf);
  1759. static int
  1760. sum_bsizes(const char *fpath, const struct stat *sb,
  1761. int typeflag, struct FTW *ftwbuf)
  1762. {
  1763. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1764. ent_blocks += sb->st_blocks;
  1765. ++num_files;
  1766. return 0;
  1767. }
  1768. static int
  1769. sum_sizes(const char *fpath, const struct stat *sb,
  1770. int typeflag, struct FTW *ftwbuf)
  1771. {
  1772. if (sb->st_size && (typeflag == FTW_F || typeflag == FTW_D))
  1773. ent_blocks += sb->st_size;
  1774. ++num_files;
  1775. return 0;
  1776. }
  1777. static int
  1778. dentfill(char *path, struct entry **dents,
  1779. int (*filter)(regex_t *, char *), regex_t *re)
  1780. {
  1781. static DIR *dirp;
  1782. static struct dirent *dp;
  1783. static char *namep, *pnb;
  1784. static struct entry *dentp;
  1785. static size_t off, namebuflen = NAMEBUF_INCR;
  1786. static ulong num_saved;
  1787. static int fd, n, count;
  1788. static struct stat sb_path, sb;
  1789. off = 0;
  1790. dirp = opendir(path);
  1791. if (dirp == NULL)
  1792. return 0;
  1793. fd = dirfd(dirp);
  1794. n = 0;
  1795. if (cfg.blkorder) {
  1796. num_files = 0;
  1797. dir_blocks = 0;
  1798. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  1799. printwarn();
  1800. return 0;
  1801. }
  1802. }
  1803. while ((dp = readdir(dirp)) != NULL) {
  1804. namep = dp->d_name;
  1805. if (filter(re, namep) == 0) {
  1806. if (!cfg.blkorder)
  1807. continue;
  1808. /* Skip self and parent */
  1809. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  1810. continue;
  1811. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  1812. continue;
  1813. if (S_ISDIR(sb.st_mode)) {
  1814. if (sb_path.st_dev == sb.st_dev) {
  1815. ent_blocks = 0;
  1816. mkpath(path, namep, g_buf, PATH_MAX);
  1817. if (nftw(g_buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1818. printmsg(messages[STR_NFTWFAIL_ID]);
  1819. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1820. } else
  1821. dir_blocks += ent_blocks;
  1822. }
  1823. } else {
  1824. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1825. ++num_files;
  1826. }
  1827. continue;
  1828. }
  1829. /* Skip self and parent */
  1830. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1831. (namep[1] == '.' && namep[2] == '\0'))))
  1832. continue;
  1833. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1834. DPRINTF_S(namep);
  1835. continue;
  1836. }
  1837. if (n == total_dents) {
  1838. total_dents += ENTRY_INCR;
  1839. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  1840. if (*dents == NULL) {
  1841. if (pnamebuf)
  1842. free(pnamebuf);
  1843. errexit();
  1844. }
  1845. DPRINTF_P(*dents);
  1846. }
  1847. /* If there's not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  1848. if (namebuflen - off < NAME_MAX + 1) {
  1849. namebuflen += NAMEBUF_INCR;
  1850. pnb = pnamebuf;
  1851. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  1852. if (pnamebuf == NULL) {
  1853. free(*dents);
  1854. errexit();
  1855. }
  1856. DPRINTF_P(pnamebuf);
  1857. /* realloc() may result in memory move, we must re-adjust if that happens */
  1858. if (pnb != pnamebuf) {
  1859. dentp = *dents;
  1860. dentp->name = pnamebuf;
  1861. for (count = 1; count < n; ++dentp, ++count)
  1862. /* Current filename starts at last filename start + length */
  1863. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  1864. }
  1865. }
  1866. dentp = *dents + n;
  1867. /* Copy file name */
  1868. dentp->name = (char *)((size_t)pnamebuf + off);
  1869. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  1870. off += dentp->nlen;
  1871. /* Copy other fields */
  1872. dentp->mode = sb.st_mode;
  1873. dentp->t = sb.st_mtime;
  1874. dentp->size = sb.st_size;
  1875. if (cfg.blkorder) {
  1876. if (S_ISDIR(sb.st_mode)) {
  1877. ent_blocks = 0;
  1878. num_saved = num_files + 1;
  1879. mkpath(path, namep, g_buf, PATH_MAX);
  1880. if (nftw(g_buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1881. printmsg(messages[STR_NFTWFAIL_ID]);
  1882. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1883. } else
  1884. dentp->blocks = ent_blocks;
  1885. if (sb_path.st_dev == sb.st_dev)
  1886. dir_blocks += dentp->blocks;
  1887. else
  1888. num_files = num_saved;
  1889. } else {
  1890. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1891. dir_blocks += dentp->blocks;
  1892. ++num_files;
  1893. }
  1894. }
  1895. /* Flag if this is a symlink to a dir */
  1896. if (S_ISLNK(sb.st_mode))
  1897. if (!fstatat(fd, namep, &sb, 0)) {
  1898. if (S_ISDIR(sb.st_mode))
  1899. dentp->flags |= SYMLINK_TO_DIR;
  1900. else
  1901. dentp->flags &= ~SYMLINK_TO_DIR;
  1902. }
  1903. ++n;
  1904. }
  1905. /* Should never be null */
  1906. if (closedir(dirp) == -1) {
  1907. if (*dents) {
  1908. free(pnamebuf);
  1909. free(*dents);
  1910. }
  1911. errexit();
  1912. }
  1913. return n;
  1914. }
  1915. static void
  1916. dentfree(struct entry *dents)
  1917. {
  1918. free(pnamebuf);
  1919. free(dents);
  1920. }
  1921. /* Return the position of the matching entry or 0 otherwise */
  1922. static int
  1923. dentfind(struct entry *dents, const char *fname, int n)
  1924. {
  1925. static int i;
  1926. if (!fname)
  1927. return 0;
  1928. DPRINTF_S(fname);
  1929. for (i = 0; i < n; ++i)
  1930. if (strcmp(fname, dents[i].name) == 0)
  1931. return i;
  1932. return 0;
  1933. }
  1934. static int
  1935. populate(char *path, char *oldname, char *fltr)
  1936. {
  1937. static regex_t re;
  1938. /* Can fail when permissions change while browsing.
  1939. * It's assumed that path IS a directory when we are here.
  1940. */
  1941. if (access(path, R_OK) == -1)
  1942. return -1;
  1943. /* Search filter */
  1944. if (setfilter(&re, fltr) != 0)
  1945. return -1;
  1946. if (cfg.blkorder) {
  1947. printmsg("calculating...");
  1948. refresh();
  1949. }
  1950. #ifdef DEBUGMODE
  1951. struct timespec ts1, ts2;
  1952. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  1953. #endif
  1954. ndents = dentfill(path, &dents, visible, &re);
  1955. regfree(&re);
  1956. if (!ndents)
  1957. return 0;
  1958. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1959. #ifdef DEBUGMODE
  1960. clock_gettime(CLOCK_REALTIME, &ts2);
  1961. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  1962. #endif
  1963. /* Find cur from history */
  1964. cur = dentfind(dents, oldname, ndents);
  1965. return 0;
  1966. }
  1967. static void
  1968. redraw(char *path)
  1969. {
  1970. static char buf[NAME_MAX + 65] __attribute__ ((aligned));
  1971. static size_t ncols;
  1972. static int nlines, i;
  1973. static bool mode_changed;
  1974. mode_changed = FALSE;
  1975. nlines = MIN(LINES - 4, ndents);
  1976. /* Clean screen */
  1977. erase();
  1978. if (cfg.copymode)
  1979. if (g_crc != crc8fast((uchar *)dents, ndents * sizeof(struct entry))) {
  1980. cfg.copymode = 0;
  1981. DPRINTF_S("copymode off");
  1982. }
  1983. /* Fail redraw if < than 10 columns */
  1984. if (COLS < 10) {
  1985. printmsg("too few columns!");
  1986. return;
  1987. }
  1988. /* Strip trailing slashes */
  1989. for (i = strlen(path) - 1; i > 0; --i)
  1990. if (path[i] == '/')
  1991. path[i] = '\0';
  1992. else
  1993. break;
  1994. DPRINTF_D(cur);
  1995. DPRINTF_S(path);
  1996. if (!realpath(path, g_buf)) {
  1997. printwarn();
  1998. return;
  1999. }
  2000. ncols = COLS;
  2001. if (ncols > PATH_MAX)
  2002. ncols = PATH_MAX;
  2003. attron(A_UNDERLINE);
  2004. /* No text wrapping in cwd line */
  2005. g_buf[ncols - 1] = '\0';
  2006. printw("%s\n\n", g_buf);
  2007. attroff(A_UNDERLINE);
  2008. /* Fallback to light mode if less than 35 columns */
  2009. if (ncols < 35 && cfg.showdetail) {
  2010. cfg.showdetail ^= 1;
  2011. printptr = &printent;
  2012. mode_changed = TRUE;
  2013. }
  2014. /* Calculate the number of cols available to print entry name */
  2015. if (cfg.showdetail)
  2016. ncols -= 32;
  2017. else
  2018. ncols -= 5;
  2019. if (cfg.showcolor) {
  2020. attron(COLOR_PAIR(1) | A_BOLD);
  2021. cfg.dircolor = 1;
  2022. }
  2023. /* Print listing */
  2024. if (cur < (nlines >> 1)) {
  2025. for (i = 0; i < nlines; ++i)
  2026. printptr(&dents[i], i == cur, ncols);
  2027. } else if (cur >= ndents - (nlines >> 1)) {
  2028. for (i = ndents - nlines; i < ndents; ++i)
  2029. printptr(&dents[i], i == cur, ncols);
  2030. } else {
  2031. static int odd;
  2032. odd = ISODD(nlines);
  2033. nlines >>= 1;
  2034. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  2035. printptr(&dents[i], i == cur, ncols);
  2036. }
  2037. /* Must reset e.g. no files in dir */
  2038. if (cfg.dircolor) {
  2039. attroff(COLOR_PAIR(1) | A_BOLD);
  2040. cfg.dircolor = 0;
  2041. }
  2042. if (cfg.showdetail) {
  2043. if (ndents) {
  2044. static char sort[9];
  2045. if (cfg.mtimeorder)
  2046. xstrlcpy(sort, "by time ", 9);
  2047. else if (cfg.sizeorder)
  2048. xstrlcpy(sort, "by size ", 9);
  2049. else
  2050. sort[0] = '\0';
  2051. /* We need to show filename as it may be truncated in directory listing */
  2052. if (!cfg.blkorder)
  2053. snprintf(buf, NAME_MAX + 65, "%d/%d %s[%s%s]",
  2054. cur + 1, ndents, sort, unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  2055. else {
  2056. i = snprintf(buf, 64, "%d/%d ", cur + 1, ndents);
  2057. if (cfg.apparentsz)
  2058. buf[i++] = 'a', buf[i++] = 'p';
  2059. else
  2060. buf[i++] = 'd', buf[i++] = 'u';
  2061. i += snprintf(buf + i, 64, ": %s (%lu files) ", coolsize(dir_blocks << BLK_SHIFT), num_files);
  2062. snprintf(buf + i, NAME_MAX, "vol: %s free [%s%s]",
  2063. coolsize(get_fs_info(path, FREE)), unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  2064. }
  2065. printmsg(buf);
  2066. } else
  2067. printmsg("0 items");
  2068. }
  2069. if (mode_changed) {
  2070. cfg.showdetail ^= 1;
  2071. printptr = &printent_long;
  2072. }
  2073. }
  2074. static void
  2075. browse(char *ipath, char *ifilter)
  2076. {
  2077. static char path[PATH_MAX] __attribute__ ((aligned));
  2078. static char newpath[PATH_MAX] __attribute__ ((aligned));
  2079. static char lastdir[PATH_MAX] __attribute__ ((aligned));
  2080. static char mark[PATH_MAX] __attribute__ ((aligned));
  2081. static char fltr[NAME_MAX + 1] __attribute__ ((aligned));
  2082. static char oldname[NAME_MAX + 1] __attribute__ ((aligned));
  2083. char *dir, *tmp, *run = NULL, *env = NULL;
  2084. struct stat sb;
  2085. int r, fd, truecd, presel, ncp = 0, copystartid = 0, copyendid = 0;
  2086. enum action sel = SEL_RUNARG + 1;
  2087. bool dir_changed = FALSE;
  2088. xstrlcpy(path, ipath, PATH_MAX);
  2089. copyfilter();
  2090. oldname[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  2091. if (cfg.filtermode)
  2092. presel = FILTER;
  2093. else
  2094. presel = 0;
  2095. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  2096. if (dents == NULL)
  2097. errexit();
  2098. DPRINTF_P(dents);
  2099. /* Allocate buffer to hold names */
  2100. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  2101. if (pnamebuf == NULL) {
  2102. free(dents);
  2103. errexit();
  2104. }
  2105. DPRINTF_P(pnamebuf);
  2106. begin:
  2107. #ifdef LINUX_INOTIFY
  2108. if (dir_changed && inotify_wd >= 0) {
  2109. inotify_rm_watch(inotify_fd, inotify_wd);
  2110. inotify_wd = -1;
  2111. dir_changed = FALSE;
  2112. }
  2113. #elif defined(BSD_KQUEUE)
  2114. if (dir_changed && event_fd >= 0) {
  2115. close(event_fd);
  2116. event_fd = -1;
  2117. dir_changed = FALSE;
  2118. }
  2119. #endif
  2120. if (populate(path, oldname, fltr) == -1) {
  2121. printwarn();
  2122. goto nochange;
  2123. }
  2124. #ifdef LINUX_INOTIFY
  2125. if (inotify_wd == -1)
  2126. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  2127. #elif defined(BSD_KQUEUE)
  2128. if (event_fd == -1) {
  2129. #if defined(O_EVTONLY)
  2130. event_fd = open(path, O_EVTONLY);
  2131. #else
  2132. event_fd = open(path, O_RDONLY);
  2133. #endif
  2134. if (event_fd >= 0)
  2135. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  2136. }
  2137. #endif
  2138. for (;;) {
  2139. redraw(path);
  2140. nochange:
  2141. /* Exit if parent has exited */
  2142. if (getppid() == 1)
  2143. _exit(0);
  2144. sel = nextsel(&run, &env, &presel);
  2145. switch (sel) {
  2146. case SEL_BACK:
  2147. /* There is no going back */
  2148. if (istopdir(path)) {
  2149. /* Continue in navigate-as-you-type mode, if enabled */
  2150. if (cfg.filtermode)
  2151. presel = FILTER;
  2152. goto nochange;
  2153. }
  2154. dir = xdirname(path);
  2155. if (access(dir, R_OK) == -1) {
  2156. printwarn();
  2157. goto nochange;
  2158. }
  2159. /* Save history */
  2160. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2161. /* Save last working directory */
  2162. xstrlcpy(lastdir, path, PATH_MAX);
  2163. dir_changed = TRUE;
  2164. xstrlcpy(path, dir, PATH_MAX);
  2165. /* Reset filter */
  2166. copyfilter();
  2167. if (cfg.filtermode)
  2168. presel = FILTER;
  2169. goto begin;
  2170. case SEL_GOIN:
  2171. /* Cannot descend in empty directories */
  2172. if (!ndents)
  2173. goto begin;
  2174. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2175. DPRINTF_S(newpath);
  2176. /* Get path info */
  2177. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  2178. if (fd == -1) {
  2179. printwarn();
  2180. goto nochange;
  2181. }
  2182. if (fstat(fd, &sb) == -1) {
  2183. printwarn();
  2184. close(fd);
  2185. goto nochange;
  2186. }
  2187. close(fd);
  2188. DPRINTF_U(sb.st_mode);
  2189. switch (sb.st_mode & S_IFMT) {
  2190. case S_IFDIR:
  2191. if (access(newpath, R_OK) == -1) {
  2192. printwarn();
  2193. goto nochange;
  2194. }
  2195. /* Save last working directory */
  2196. xstrlcpy(lastdir, path, PATH_MAX);
  2197. dir_changed = TRUE;
  2198. xstrlcpy(path, newpath, PATH_MAX);
  2199. oldname[0] = '\0';
  2200. /* Reset filter */
  2201. copyfilter();
  2202. if (cfg.filtermode)
  2203. presel = FILTER;
  2204. goto begin;
  2205. case S_IFREG:
  2206. {
  2207. /* If NNN_USE_EDITOR is set,
  2208. * open text in EDITOR
  2209. */
  2210. if (editor) {
  2211. if (getmime(dents[cur].name)) {
  2212. spawn(editor, newpath, NULL, path, F_NORMAL);
  2213. continue;
  2214. }
  2215. /* Recognize and open plain
  2216. * text files with vi
  2217. */
  2218. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  2219. continue;
  2220. if (strstr(g_buf, "text/") == g_buf) {
  2221. spawn(editor, newpath, NULL, path, F_NORMAL);
  2222. continue;
  2223. }
  2224. }
  2225. /* Invoke desktop opener as last resort */
  2226. spawn(utils[OPENER], newpath, NULL, NULL, F_NOWAIT | F_NOTRACE);
  2227. continue;
  2228. }
  2229. default:
  2230. printmsg("unsupported file");
  2231. goto nochange;
  2232. }
  2233. case SEL_NEXT:
  2234. if (cur < ndents - 1)
  2235. ++cur;
  2236. else if (ndents)
  2237. /* Roll over, set cursor to first entry */
  2238. cur = 0;
  2239. break;
  2240. case SEL_PREV:
  2241. if (cur > 0)
  2242. --cur;
  2243. else if (ndents)
  2244. /* Roll over, set cursor to last entry */
  2245. cur = ndents - 1;
  2246. break;
  2247. case SEL_PGDN:
  2248. if (cur < ndents - 1)
  2249. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  2250. break;
  2251. case SEL_PGUP:
  2252. if (cur > 0)
  2253. cur -= MIN((LINES - 4) / 2, cur);
  2254. break;
  2255. case SEL_HOME:
  2256. cur = 0;
  2257. break;
  2258. case SEL_END:
  2259. cur = ndents - 1;
  2260. break;
  2261. case SEL_CD:
  2262. truecd = 0;
  2263. tmp = xreadline(NULL, "cd: ");
  2264. if (tmp == NULL || tmp[0] == '\0')
  2265. break;
  2266. if (tmp[0] == '~') {
  2267. /* Expand ~ to HOME absolute path */
  2268. dir = getenv("HOME");
  2269. if (dir)
  2270. snprintf(newpath, PATH_MAX, "%s%s", dir, tmp + 1);
  2271. else {
  2272. printmsg(messages[STR_NOHOME_ID]);
  2273. goto nochange;
  2274. }
  2275. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  2276. if (lastdir[0] == '\0')
  2277. break;
  2278. /* Switch to last visited dir */
  2279. xstrlcpy(newpath, lastdir, PATH_MAX);
  2280. truecd = 1;
  2281. } else if ((r = all_dots(tmp))) {
  2282. if (r == 1)
  2283. /* Always in the current dir */
  2284. break;
  2285. /* Show a message if already at / */
  2286. if (istopdir(path)) {
  2287. /* Continue in navigate-as-you-type mode, if enabled */
  2288. if (cfg.filtermode)
  2289. presel = FILTER;
  2290. goto nochange;
  2291. }
  2292. --r; /* One . for the current dir */
  2293. dir = path;
  2294. /* Note: fd is used as a tmp variable here */
  2295. for (fd = 0; fd < r; ++fd) {
  2296. /* Reached / ? */
  2297. if (istopdir(path)) {
  2298. /* Can't cd beyond / */
  2299. break;
  2300. }
  2301. dir = xdirname(dir);
  2302. if (access(dir, R_OK) == -1) {
  2303. printwarn();
  2304. goto nochange;
  2305. }
  2306. }
  2307. truecd = 1;
  2308. /* Save the path in case of cd ..
  2309. * We mark the current dir in parent dir
  2310. */
  2311. if (r == 1) {
  2312. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2313. truecd = 2;
  2314. }
  2315. xstrlcpy(newpath, dir, PATH_MAX);
  2316. } else
  2317. mkpath(path, tmp, newpath, PATH_MAX);
  2318. if (!xdiraccess(newpath))
  2319. goto nochange;
  2320. if (truecd == 0) {
  2321. /* Probable change in dir */
  2322. /* No-op if it's the same directory */
  2323. if (strcmp(path, newpath) == 0)
  2324. break;
  2325. oldname[0] = '\0';
  2326. } else if (truecd == 1)
  2327. /* Sure change in dir */
  2328. oldname[0] = '\0';
  2329. /* Save last working directory */
  2330. xstrlcpy(lastdir, path, PATH_MAX);
  2331. dir_changed = TRUE;
  2332. /* Save the newly opted dir in path */
  2333. xstrlcpy(path, newpath, PATH_MAX);
  2334. /* Reset filter */
  2335. copyfilter();
  2336. DPRINTF_S(path);
  2337. if (cfg.filtermode)
  2338. presel = FILTER;
  2339. goto begin;
  2340. case SEL_CDHOME:
  2341. dir = getenv("HOME");
  2342. if (dir == NULL) {
  2343. clearprompt();
  2344. goto nochange;
  2345. } // fallthrough
  2346. case SEL_CDBEGIN:
  2347. if (sel == SEL_CDBEGIN)
  2348. dir = ipath;
  2349. if (!xdiraccess(dir))
  2350. goto nochange;
  2351. if (strcmp(path, dir) == 0)
  2352. break;
  2353. /* Save last working directory */
  2354. xstrlcpy(lastdir, path, PATH_MAX);
  2355. dir_changed = TRUE;
  2356. xstrlcpy(path, dir, PATH_MAX);
  2357. oldname[0] = '\0';
  2358. /* Reset filter */
  2359. copyfilter();
  2360. DPRINTF_S(path);
  2361. if (cfg.filtermode)
  2362. presel = FILTER;
  2363. goto begin;
  2364. case SEL_CDLAST: // fallthrough
  2365. case SEL_VISIT:
  2366. if (sel == SEL_VISIT) {
  2367. if (strcmp(mark, path) == 0)
  2368. break;
  2369. tmp = mark;
  2370. } else
  2371. tmp = lastdir;
  2372. if (tmp[0] == '\0') {
  2373. printmsg("not set...");
  2374. goto nochange;
  2375. }
  2376. if (!xdiraccess(tmp))
  2377. goto nochange;
  2378. xstrlcpy(newpath, tmp, PATH_MAX);
  2379. xstrlcpy(lastdir, path, PATH_MAX);
  2380. dir_changed = TRUE;
  2381. xstrlcpy(path, newpath, PATH_MAX);
  2382. oldname[0] = '\0';
  2383. /* Reset filter */
  2384. copyfilter();
  2385. DPRINTF_S(path);
  2386. if (cfg.filtermode)
  2387. presel = FILTER;
  2388. goto begin;
  2389. case SEL_CDBM:
  2390. tmp = xreadline(NULL, "key: ");
  2391. if (tmp == NULL || tmp[0] == '\0')
  2392. break;
  2393. /* Interpret ~, - and & keys */
  2394. if ((tmp[1] == '\0') && (tmp[0] == '~' || tmp[0] == '-' || tmp[0] == '&')) {
  2395. presel = tmp[0];
  2396. goto begin;
  2397. }
  2398. if (get_bm_loc(tmp, newpath) == NULL) {
  2399. printmsg(messages[STR_INVBM_ID]);
  2400. goto nochange;
  2401. }
  2402. if (!xdiraccess(newpath))
  2403. goto nochange;
  2404. if (strcmp(path, newpath) == 0)
  2405. break;
  2406. oldname[0] = '\0';
  2407. /* Save last working directory */
  2408. xstrlcpy(lastdir, path, PATH_MAX);
  2409. dir_changed = TRUE;
  2410. /* Save the newly opted dir in path */
  2411. xstrlcpy(path, newpath, PATH_MAX);
  2412. /* Reset filter */
  2413. copyfilter();
  2414. DPRINTF_S(path);
  2415. if (cfg.filtermode)
  2416. presel = FILTER;
  2417. goto begin;
  2418. case SEL_PIN:
  2419. xstrlcpy(mark, path, PATH_MAX);
  2420. printmsg(mark);
  2421. goto nochange;
  2422. case SEL_FLTR:
  2423. presel = filterentries(path);
  2424. copyfilter();
  2425. DPRINTF_S(fltr);
  2426. /* Save current */
  2427. if (ndents)
  2428. copycurname();
  2429. goto nochange;
  2430. case SEL_MFLTR:
  2431. cfg.filtermode ^= 1;
  2432. if (cfg.filtermode)
  2433. presel = FILTER;
  2434. else {
  2435. /* Save current */
  2436. if (ndents)
  2437. copycurname();
  2438. /* Start watching the directory */
  2439. goto begin;
  2440. }
  2441. goto nochange;
  2442. case SEL_SEARCH:
  2443. spawn(player, path, "search", NULL, F_NORMAL);
  2444. break;
  2445. case SEL_TOGGLEDOT:
  2446. cfg.showhidden ^= 1;
  2447. initfilter(cfg.showhidden, &ifilter);
  2448. copyfilter();
  2449. goto begin;
  2450. case SEL_DETAIL:
  2451. cfg.showdetail ^= 1;
  2452. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2453. /* Save current */
  2454. if (ndents)
  2455. copycurname();
  2456. goto begin;
  2457. case SEL_STATS:
  2458. if (!ndents)
  2459. break;
  2460. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2461. if (lstat(newpath, &sb) == -1) {
  2462. if (dents)
  2463. dentfree(dents);
  2464. errexit();
  2465. }
  2466. if (show_stats(newpath, dents[cur].name, &sb) < 0) {
  2467. printwarn();
  2468. goto nochange;
  2469. }
  2470. break;
  2471. case SEL_LIST: // fallthrough
  2472. case SEL_EXTRACT: // fallthrough
  2473. case SEL_MEDIA: // fallthrough
  2474. case SEL_FMEDIA:
  2475. if (!ndents)
  2476. break;
  2477. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2478. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2479. r = show_mediainfo(newpath, run);
  2480. else
  2481. r = handle_archive(newpath, run, path);
  2482. if (r == -1) {
  2483. xstrlcpy(newpath, "missing ", PATH_MAX);
  2484. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2485. xstrlcpy(newpath + 8, utils[cfg.metaviewer], 32);
  2486. else
  2487. xstrlcpy(newpath + 8, utils[ATOOL], 32);
  2488. printmsg(newpath);
  2489. goto nochange;
  2490. }
  2491. /* In case of successful archive extract, reload contents */
  2492. if (sel == SEL_EXTRACT) {
  2493. /* Continue in navigate-as-you-type mode, if enabled */
  2494. if (cfg.filtermode)
  2495. presel = FILTER;
  2496. /* Save current */
  2497. copycurname();
  2498. /* Repopulate as directory content may have changed */
  2499. goto begin;
  2500. }
  2501. break;
  2502. case SEL_DFB:
  2503. if (!dmanager) {
  2504. printmsg("set NNN_DE_FILE_MANAGER");
  2505. goto nochange;
  2506. }
  2507. spawn(dmanager, path, NULL, path, F_NOWAIT | F_NOTRACE);
  2508. break;
  2509. case SEL_FSIZE:
  2510. cfg.sizeorder ^= 1;
  2511. cfg.mtimeorder = 0;
  2512. cfg.apparentsz = 0;
  2513. cfg.blkorder = 0;
  2514. cfg.copymode = 0;
  2515. /* Save current */
  2516. if (ndents)
  2517. copycurname();
  2518. goto begin;
  2519. case SEL_ASIZE:
  2520. cfg.apparentsz ^= 1;
  2521. if (cfg.apparentsz) {
  2522. nftw_fn = &sum_sizes;
  2523. cfg.blkorder = 1;
  2524. BLK_SHIFT = 0;
  2525. } else
  2526. cfg.blkorder = 0; // fallthrough
  2527. case SEL_BSIZE:
  2528. if (sel == SEL_BSIZE) {
  2529. if (!cfg.apparentsz)
  2530. cfg.blkorder ^= 1;
  2531. nftw_fn = &sum_bsizes;
  2532. cfg.apparentsz = 0;
  2533. BLK_SHIFT = 9;
  2534. }
  2535. if (cfg.blkorder) {
  2536. cfg.showdetail = 1;
  2537. printptr = &printent_long;
  2538. }
  2539. cfg.mtimeorder = 0;
  2540. cfg.sizeorder = 0;
  2541. cfg.copymode = 0;
  2542. /* Save current */
  2543. if (ndents)
  2544. copycurname();
  2545. goto begin;
  2546. case SEL_MTIME:
  2547. cfg.mtimeorder ^= 1;
  2548. cfg.sizeorder = 0;
  2549. cfg.apparentsz = 0;
  2550. cfg.blkorder = 0;
  2551. cfg.copymode = 0;
  2552. /* Save current */
  2553. if (ndents)
  2554. copycurname();
  2555. goto begin;
  2556. case SEL_REDRAW:
  2557. /* Save current */
  2558. if (ndents)
  2559. copycurname();
  2560. goto begin;
  2561. case SEL_COPY:
  2562. if (!(cfg.noxdisplay || copier)) {
  2563. printmsg(messages[STR_COPY_ID]);
  2564. goto nochange;
  2565. }
  2566. if (!ndents)
  2567. goto nochange;
  2568. if (cfg.copymode) {
  2569. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2570. if (!appendfpath(newpath, r))
  2571. goto nochange;
  2572. ++ncp;
  2573. printmsg(newpath);
  2574. } else if (cfg.quote) {
  2575. g_buf[0] = '\'';
  2576. r = mkpath(path, dents[cur].name, g_buf + 1, PATH_MAX);
  2577. g_buf[r] = '\'';
  2578. g_buf[r + 1] = '\0';
  2579. if (cfg.noxdisplay)
  2580. writecp(g_buf, r + 1); /* Truncate NULL from end */
  2581. else
  2582. spawn(copier, g_buf, NULL, NULL, F_NOTRACE);
  2583. g_buf[r] = '\0';
  2584. printmsg(g_buf + 1);
  2585. } else {
  2586. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2587. if (cfg.noxdisplay)
  2588. writecp(newpath, r - 1); /* Truncate NULL from end */
  2589. else
  2590. spawn(copier, newpath, NULL, NULL, F_NOTRACE);
  2591. printmsg(newpath);
  2592. }
  2593. goto nochange;
  2594. case SEL_COPYMUL:
  2595. if (!(cfg.noxdisplay || copier)) {
  2596. printmsg(messages[STR_COPY_ID]);
  2597. goto nochange;
  2598. }
  2599. if (!ndents)
  2600. goto nochange;
  2601. cfg.copymode ^= 1;
  2602. if (cfg.copymode) {
  2603. g_crc = crc8fast((uchar *)dents, ndents * sizeof(struct entry));
  2604. copystartid = cur;
  2605. copybufpos = 0;
  2606. ncp = 0;
  2607. printmsg("multi-copy on");
  2608. DPRINTF_S("copymode on");
  2609. goto nochange;
  2610. }
  2611. if (!ncp) { /* Handle range selection */
  2612. if (cur < copystartid) {
  2613. copyendid = copystartid;
  2614. copystartid = cur;
  2615. } else
  2616. copyendid = cur;
  2617. if (copystartid < copyendid) {
  2618. for (r = copystartid; r <= copyendid; ++r)
  2619. if (!appendfpath(newpath, mkpath(path, dents[r].name, newpath, PATH_MAX)))
  2620. goto nochange;
  2621. snprintf(newpath, PATH_MAX, "%d files copied", copyendid - copystartid + 1);
  2622. printmsg(newpath);
  2623. }
  2624. }
  2625. if (copybufpos) { /* File path(s) written to the buffer */
  2626. if (cfg.noxdisplay)
  2627. writecp(pcopybuf, copybufpos - 1); /* Truncate NULL from end */
  2628. else
  2629. spawn(copier, pcopybuf, NULL, NULL, F_NOTRACE);
  2630. if (ncp) { /* Some files cherry picked */
  2631. snprintf(newpath, PATH_MAX, "%d files copied", ncp);
  2632. printmsg(newpath);
  2633. }
  2634. } else
  2635. printmsg("multi-copy off");
  2636. goto nochange;
  2637. case SEL_QUOTE:
  2638. cfg.quote ^= 1;
  2639. DPRINTF_D(cfg.quote);
  2640. if (cfg.quote)
  2641. printmsg("quotes on");
  2642. else
  2643. printmsg("quotes off");
  2644. goto nochange;
  2645. case SEL_OPEN: // fallthrough
  2646. case SEL_ARCHIVE:
  2647. if (!ndents)
  2648. break; // fallthrough
  2649. case SEL_NEW:
  2650. if (sel == SEL_OPEN)
  2651. tmp = xreadline(NULL, "open with: ");
  2652. else if (sel == SEL_ARCHIVE)
  2653. tmp = xreadline(dents[cur].name, "name: ");
  2654. else
  2655. tmp = xreadline(NULL, "name: ");
  2656. if (tmp == NULL || tmp[0] == '\0')
  2657. break;
  2658. /* Allow only relative, same dir paths */
  2659. if (tmp[0] == '/' || strcmp(xbasename(tmp), tmp) != 0) {
  2660. printmsg(messages[STR_INPUT_ID]);
  2661. goto nochange;
  2662. }
  2663. if (sel == SEL_OPEN) {
  2664. printprompt("press 'c' for cli mode");
  2665. cleartimeout();
  2666. r = getch();
  2667. settimeout();
  2668. if (r == 'c')
  2669. r = F_NORMAL;
  2670. else
  2671. r = F_NOWAIT | F_NOTRACE;
  2672. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2673. spawn(tmp, newpath, NULL, path, r);
  2674. continue;
  2675. } else if (sel == SEL_ARCHIVE) {
  2676. /* newpath is used as temporary buffer */
  2677. if (!get_output(newpath, PATH_MAX, "which", utils[APACK], NULL, 0)) {
  2678. printmsg("apack missing");
  2679. continue;
  2680. }
  2681. spawn(utils[APACK], tmp, dents[cur].name, path, F_NORMAL);
  2682. /* Continue in navigate-as-you-type mode, if enabled */
  2683. if (cfg.filtermode)
  2684. presel = FILTER;
  2685. /* Save current */
  2686. copycurname();
  2687. /* Repopulate as directory content may have changed */
  2688. goto begin;
  2689. }
  2690. /* Open the descriptor to currently open directory */
  2691. fd = open(path, O_RDONLY | O_DIRECTORY);
  2692. if (fd == -1) {
  2693. printwarn();
  2694. goto nochange;
  2695. }
  2696. /* Check if another file with same name exists */
  2697. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2698. printmsg("entry exists");
  2699. goto nochange;
  2700. }
  2701. /* Check if it's a dir or file */
  2702. printprompt("press 'f'(ile) or 'd'(ir)");
  2703. cleartimeout();
  2704. r = getch();
  2705. settimeout();
  2706. if (r == 'f') {
  2707. r = openat(fd, tmp, O_CREAT, 0666);
  2708. close(r);
  2709. } else if (r == 'd')
  2710. r = mkdirat(fd, tmp, 0777);
  2711. else {
  2712. close(fd);
  2713. break;
  2714. }
  2715. if (r == -1) {
  2716. printwarn();
  2717. close(fd);
  2718. goto nochange;
  2719. }
  2720. close(fd);
  2721. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2722. goto begin;
  2723. case SEL_RENAME:
  2724. if (!ndents)
  2725. break;
  2726. tmp = xreadline(dents[cur].name, "");
  2727. if (tmp == NULL || tmp[0] == '\0')
  2728. break;
  2729. /* Allow only relative, same dir paths */
  2730. if (tmp[0] == '/' || strcmp(xbasename(tmp), tmp) != 0) {
  2731. printmsg(messages[STR_INPUT_ID]);
  2732. goto nochange;
  2733. }
  2734. /* Skip renaming to same name */
  2735. if (strcmp(tmp, dents[cur].name) == 0)
  2736. break;
  2737. /* Open the descriptor to currently open directory */
  2738. fd = open(path, O_RDONLY | O_DIRECTORY);
  2739. if (fd == -1) {
  2740. printwarn();
  2741. goto nochange;
  2742. }
  2743. /* Check if another file with same name exists */
  2744. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2745. /* File with the same name exists */
  2746. printprompt("press 'y' to overwrite");
  2747. cleartimeout();
  2748. r = getch();
  2749. settimeout();
  2750. if (r != 'y') {
  2751. close(fd);
  2752. break;
  2753. }
  2754. }
  2755. /* Rename the file */
  2756. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  2757. printwarn();
  2758. close(fd);
  2759. goto nochange;
  2760. }
  2761. close(fd);
  2762. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2763. goto begin;
  2764. case SEL_RENAMEALL:
  2765. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[VIDIR], NULL, 0)) {
  2766. printmsg("vidir missing");
  2767. goto nochange;
  2768. }
  2769. spawn(utils[VIDIR], ".", NULL, path, F_NORMAL);
  2770. /* Save current */
  2771. if (ndents)
  2772. copycurname();
  2773. goto begin;
  2774. case SEL_HELP:
  2775. show_help(path);
  2776. /* Continue in navigate-as-you-type mode, if enabled */
  2777. if (cfg.filtermode)
  2778. presel = FILTER;
  2779. break;
  2780. case SEL_RUN: // fallthrough
  2781. case SEL_RUNSCRIPT:
  2782. run = xgetenv(env, run);
  2783. if (sel == SEL_RUNSCRIPT) {
  2784. tmp = getenv("NNN_SCRIPT");
  2785. if (tmp) {
  2786. if (getenv("NNN_MULTISCRIPT")) {
  2787. size_t _len = xstrlcpy(newpath, tmp, PATH_MAX);
  2788. tmp = xreadline(NULL, "script suffix: ");
  2789. if (tmp && tmp[0])
  2790. xstrlcpy(newpath + _len - 1, tmp, PATH_MAX - _len);
  2791. tmp = newpath;
  2792. }
  2793. char *curfile = NULL;
  2794. if (ndents)
  2795. curfile = dents[cur].name;
  2796. spawn(run, tmp, curfile, path, F_NORMAL | F_SIGINT);
  2797. } else
  2798. printmsg("set NNN_SCRIPT");
  2799. } else {
  2800. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2801. /* Continue in navigate-as-you-type mode, if enabled */
  2802. if (cfg.filtermode)
  2803. presel = FILTER;
  2804. }
  2805. /* Save current */
  2806. if (ndents)
  2807. copycurname();
  2808. /* Repopulate as directory content may have changed */
  2809. goto begin;
  2810. case SEL_RUNARG:
  2811. run = xgetenv(env, run);
  2812. if ((!run || !run[0]) && (strcmp("VISUAL", env) == 0))
  2813. run = editor ? editor : xgetenv("EDITOR", "vi");
  2814. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2815. break;
  2816. case SEL_LOCK:
  2817. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2818. break;
  2819. case SEL_CDQUIT:
  2820. {
  2821. tmp = getenv("NNN_TMPFILE");
  2822. if (!tmp) {
  2823. printmsg("set NNN_TMPFILE");
  2824. goto nochange;
  2825. }
  2826. FILE *fp = fopen(tmp, "w");
  2827. if (fp) {
  2828. fprintf(fp, "cd \"%s\"", path);
  2829. fclose(fp);
  2830. }
  2831. /* Fall through to exit */
  2832. } // fallthrough
  2833. case SEL_QUIT:
  2834. dentfree(dents);
  2835. return;
  2836. } /* switch (sel) */
  2837. /* Screensaver */
  2838. if (idletimeout != 0 && idle == idletimeout) {
  2839. idle = 0;
  2840. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2841. }
  2842. }
  2843. }
  2844. static void
  2845. usage(void)
  2846. {
  2847. fprintf(stdout,
  2848. "usage: nnn [-b key] [-c N] [-e] [-i] [-l]\n"
  2849. " [-p nlay] [-S] [-v] [-h] [PATH]\n\n"
  2850. "The missing terminal file manager for X.\n\n"
  2851. "positional args:\n"
  2852. " PATH start dir [default: current dir]\n\n"
  2853. "optional args:\n"
  2854. " -b key bookmark key to open\n"
  2855. " -c N dir color, disables if N>7\n"
  2856. " -e use exiftool instead of mediainfo\n"
  2857. " -i start in navigate-as-you-type mode\n"
  2858. " -l start in light mode\n"
  2859. " -p nlay path to custom nlay\n"
  2860. " -S start in disk usage analyser mode\n"
  2861. " -v show program version\n"
  2862. " -h show this help\n\n"
  2863. "Version: %s\n%s\n", VERSION, GENERAL_INFO);
  2864. exit(0);
  2865. }
  2866. int
  2867. main(int argc, char *argv[])
  2868. {
  2869. static char cwd[PATH_MAX] __attribute__ ((aligned));
  2870. char *ipath = NULL, *ifilter;
  2871. int opt;
  2872. /* Confirm we are in a terminal */
  2873. if (!isatty(0) || !isatty(1)) {
  2874. fprintf(stderr, "stdin or stdout is not a tty\n");
  2875. exit(1);
  2876. }
  2877. while ((opt = getopt(argc, argv, "Slib:c:ep:vh")) != -1) {
  2878. switch (opt) {
  2879. case 'S':
  2880. cfg.blkorder = 1;
  2881. break;
  2882. case 'l':
  2883. cfg.showdetail = 0;
  2884. printptr = &printent;
  2885. break;
  2886. case 'i':
  2887. cfg.filtermode = 1;
  2888. break;
  2889. case 'b':
  2890. ipath = optarg;
  2891. break;
  2892. case 'c':
  2893. if (atoi(optarg) > 7)
  2894. cfg.showcolor = 0;
  2895. else
  2896. cfg.color = (uchar)atoi(optarg);
  2897. break;
  2898. case 'e':
  2899. cfg.metaviewer = EXIFTOOL;
  2900. break;
  2901. case 'p':
  2902. player = optarg;
  2903. break;
  2904. case 'v':
  2905. fprintf(stdout, "%s\n", VERSION);
  2906. return 0;
  2907. case 'h': // fallthrough
  2908. default:
  2909. usage();
  2910. }
  2911. }
  2912. /* Parse bookmarks string */
  2913. parsebmstr();
  2914. if (ipath) { /* Open a bookmark directly */
  2915. if (get_bm_loc(ipath, cwd) == NULL) {
  2916. fprintf(stderr, "%s\n", messages[STR_INVBM_ID]);
  2917. exit(1);
  2918. }
  2919. ipath = cwd;
  2920. } else if (argc == optind) {
  2921. /* Start in the current directory */
  2922. ipath = getcwd(cwd, PATH_MAX);
  2923. if (ipath == NULL)
  2924. ipath = "/";
  2925. } else {
  2926. ipath = realpath(argv[optind], cwd);
  2927. if (!ipath) {
  2928. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2929. exit(1);
  2930. }
  2931. }
  2932. /* Increase current open file descriptor limit */
  2933. open_max = max_openfds();
  2934. if (getuid() == 0 || getenv("NNN_SHOW_HIDDEN"))
  2935. cfg.showhidden = 1;
  2936. initfilter(cfg.showhidden, &ifilter);
  2937. #ifdef LINUX_INOTIFY
  2938. /* Initialize inotify */
  2939. inotify_fd = inotify_init1(IN_NONBLOCK);
  2940. if (inotify_fd < 0) {
  2941. fprintf(stderr, "inotify init! %s\n", strerror(errno));
  2942. exit(1);
  2943. }
  2944. #elif defined(BSD_KQUEUE)
  2945. kq = kqueue();
  2946. if (kq < 0) {
  2947. fprintf(stderr, "kqueue init! %s\n", strerror(errno));
  2948. exit(1);
  2949. }
  2950. #endif
  2951. /* Edit text in EDITOR, if opted */
  2952. if (getenv("NNN_USE_EDITOR")) {
  2953. editor = xgetenv("VISUAL", NULL);
  2954. if (!editor)
  2955. editor = xgetenv("EDITOR", "vi");
  2956. }
  2957. /* Set player if not set already */
  2958. if (!player)
  2959. player = utils[NLAY];
  2960. /* Get the desktop file manager, if set */
  2961. dmanager = getenv("NNN_DE_FILE_MANAGER");
  2962. /* Get screensaver wait time, if set; copier used as tmp var */
  2963. copier = getenv("NNN_IDLE_TIMEOUT");
  2964. if (copier) {
  2965. opt = atoi(copier);
  2966. idletimeout = opt * ((opt > 0) - (opt < 0));
  2967. }
  2968. /* Get the default copier, if set */
  2969. copier = getenv("NNN_COPIER");
  2970. /* Enable quotes if opted */
  2971. if (getenv("NNN_QUOTE_ON"))
  2972. cfg.quote = 1;
  2973. if (getenv("HOME")) {
  2974. g_homelen = xstrlcpy(g_homepath, getenv("HOME"), MAX_HOME_LEN);
  2975. /* Check if X11 is available */
  2976. if (getenv("NNN_NO_X")) {
  2977. cfg.noxdisplay = 1;
  2978. xstrlcpy(g_cppath, g_homepath, MAX_HOME_LEN);
  2979. xstrlcpy(g_cppath + g_homelen - 1, "/.nnncp", MAX_HOME_LEN - g_homelen);
  2980. }
  2981. }
  2982. signal(SIGINT, SIG_IGN);
  2983. /* Test initial path */
  2984. if (!xdiraccess(ipath)) {
  2985. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2986. exit(1);
  2987. }
  2988. /* Set locale */
  2989. setlocale(LC_ALL, "");
  2990. crc8init();
  2991. #ifdef DEBUGMODE
  2992. enabledbg();
  2993. #endif
  2994. initcurses();
  2995. browse(ipath, ifilter);
  2996. exitcurses();
  2997. if (cfg.noxdisplay && g_cppath[0])
  2998. unlink(g_cppath);
  2999. #ifdef LINUX_INOTIFY
  3000. /* Shutdown inotify */
  3001. if (inotify_wd >= 0)
  3002. inotify_rm_watch(inotify_fd, inotify_wd);
  3003. close(inotify_fd);
  3004. #elif defined(BSD_KQUEUE)
  3005. if (event_fd >= 0)
  3006. close(event_fd);
  3007. close(kq);
  3008. #endif
  3009. #ifdef DEBUGMODE
  3010. disabledbg();
  3011. #endif
  3012. exit(0);
  3013. }