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

nnn.c 107 KiB

7年前
6年前
6年前
6年前
6年前
6年前
5年前
6年前
6年前
6年前
5年前
6年前
5年前
5年前
5年前
5年前
5年前
5年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
5年前
5年前
5年前
6年前
6年前
5年前
5年前
5年前
5年前
5年前
5年前
5年前
5年前
5年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
5年前
5年前
5年前
5年前
5年前
5年前
5年前
5年前
5年前
6年前
6年前
5年前
5年前
5年前
5年前
5年前
5年前
5年前
5年前
5年前
9年前
9年前
9年前
6年前
6年前
6年前
6年前
6年前
5年前
5年前
5年前
5年前
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913
  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-2019, 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. #ifndef _GNU_SOURCE
  32. #define _GNU_SOURCE
  33. #endif
  34. #if defined(__arm__) || defined(__i386__)
  35. #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit */
  36. #endif
  37. #include <sys/inotify.h>
  38. #define LINUX_INOTIFY
  39. #if !defined(__GLIBC__)
  40. #include <sys/types.h>
  41. #endif
  42. #endif
  43. #include <sys/resource.h>
  44. #include <sys/stat.h>
  45. #include <sys/statvfs.h>
  46. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  47. #include <sys/types.h>
  48. #include <sys/event.h>
  49. #include <sys/time.h>
  50. #define BSD_KQUEUE
  51. #else
  52. #include <sys/sysmacros.h>
  53. #endif
  54. #include <sys/wait.h>
  55. #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
  56. #ifndef NCURSES_WIDECHAR
  57. #define NCURSES_WIDECHAR 1
  58. #endif
  59. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  60. #ifndef _XOPEN_SOURCE_EXTENDED
  61. #define _XOPEN_SOURCE_EXTENDED
  62. #endif
  63. #endif
  64. #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
  65. #define __USE_XOPEN
  66. #endif
  67. #include <dirent.h>
  68. #include <errno.h>
  69. #include <fcntl.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 <stdio.h>
  77. #ifndef NORL
  78. #include <readline/history.h>
  79. #include <readline/readline.h>
  80. #endif
  81. #include <regex.h>
  82. #include <signal.h>
  83. #include <stdarg.h>
  84. #include <stdlib.h>
  85. #include <string.h>
  86. #include <strings.h>
  87. #include <time.h>
  88. #include <unistd.h>
  89. #ifndef __USE_XOPEN_EXTENDED
  90. #define __USE_XOPEN_EXTENDED 1
  91. #endif
  92. #include <ftw.h>
  93. #include <wchar.h>
  94. #include "nnn.h"
  95. #include "dbg.h"
  96. /* Macro definitions */
  97. #define VERSION "2.6"
  98. #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
  99. #ifndef S_BLKSIZE
  100. #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
  101. #endif
  102. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  103. #undef MIN
  104. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  105. #undef MAX
  106. #define MAX(x, y) ((x) > (y) ? (x) : (y))
  107. #define ISODD(x) ((x) & 1)
  108. #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
  109. #define TOUPPER(ch) \
  110. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  111. #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
  112. #define FILTER '/'
  113. #define MSGWAIT '$'
  114. #define REGEX_MAX 48
  115. #define BM_MAX 10
  116. #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
  117. #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per filename = 64*32B = 2KB */
  118. #define DESCRIPTOR_LEN 32
  119. #define _ALIGNMENT 0x10 /* 16-byte alignment */
  120. #define _ALIGNMENT_MASK 0xF
  121. #define TMP_LEN_MAX 64
  122. #define CTX_MAX 4
  123. #define DOT_FILTER_LEN 7
  124. #define ASCII_MAX 128
  125. #define EXEC_ARGS_MAX 8
  126. #define SCROLLOFF 3
  127. #define LONG_SIZE sizeof(ulong)
  128. #define ARCHIVE_CMD_LEN 12
  129. /* Program return codes */
  130. #define _SUCCESS 0
  131. #define _FAILURE !_SUCCESS
  132. /* Entry flags */
  133. #define DIR_OR_LINK_TO_DIR 0x1
  134. #define FILE_COPIED 0x10
  135. /* Macros to define process spawn behaviour as flags */
  136. #define F_NONE 0x00 /* no flag set */
  137. #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
  138. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  139. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  140. #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
  141. #define F_CMD 0x10 /* run command - show results before exit (must have F_NORMAL) */
  142. #define F_CLI (F_NORMAL | F_MULTI)
  143. /* CRC8 macros */
  144. #define UCHAR_BIT_WIDTH (sizeof(unsigned char) << 3)
  145. #define TOPBIT (1 << (UCHAR_BIT_WIDTH - 1))
  146. #define POLYNOMIAL 0xD8 /* 11011 followed by 0's */
  147. #define CRC8_TABLE_LEN 256
  148. /* Version compare macros */
  149. /*
  150. * states: S_N: normal, S_I: comparing integral part, S_F: comparing
  151. * fractional parts, S_Z: idem but with leading Zeroes only
  152. */
  153. #define S_N 0x0
  154. #define S_I 0x3
  155. #define S_F 0x6
  156. #define S_Z 0x9
  157. /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
  158. #define VCMP 2
  159. #define VLEN 3
  160. /* Volume info */
  161. #define FREE 0
  162. #define CAPACITY 1
  163. /* TYPE DEFINITIONS */
  164. typedef unsigned long ulong;
  165. typedef unsigned int uint;
  166. typedef unsigned char uchar;
  167. typedef unsigned short ushort;
  168. /* STRUCTURES */
  169. /* Directory entry */
  170. typedef struct entry {
  171. char *name;
  172. time_t t;
  173. off_t size;
  174. blkcnt_t blocks; /* number of 512B blocks allocated */
  175. mode_t mode;
  176. ushort nlen; /* Length of file name; can be uchar (< NAME_MAX + 1) */
  177. uchar flags; /* Flags specific to the file */
  178. } __attribute__ ((aligned(_ALIGNMENT))) *pEntry;
  179. /* Bookmark */
  180. typedef struct {
  181. int key;
  182. char *loc;
  183. } bm;
  184. /*
  185. * Settings
  186. * NOTE: update default values if changing order
  187. */
  188. typedef struct {
  189. uint filtermode : 1; /* Set to enter filter mode */
  190. uint mtimeorder : 1; /* Set to sort by time modified */
  191. uint sizeorder : 1; /* Set to sort by file size */
  192. uint apparentsz : 1; /* Set to sort by apparent size (disk usage) */
  193. uint blkorder : 1; /* Set to sort by blocks used (disk usage) */
  194. uint extnorder : 1; /* Order by extension */
  195. uint showhidden : 1; /* Set to show hidden files */
  196. uint copymode : 1; /* Set when copying files */
  197. uint showdetail : 1; /* Clear to show fewer file info */
  198. uint ctxactive : 1; /* Context active or not */
  199. uint reserved : 7;
  200. /* The following settings are global */
  201. uint curctx : 2; /* Current context number */
  202. uint dircolor : 1; /* Current status of dir color */
  203. uint picker : 1; /* Write selection to user-specified file */
  204. uint pickraw : 1; /* Write selection to sdtout before exit */
  205. uint nonavopen : 1; /* Open file on right arrow or `l` */
  206. uint autoselect : 1; /* Auto-select dir in nav-as-you-type mode */
  207. uint metaviewer : 1; /* Index of metadata viewer in utils[] */
  208. uint useeditor : 1; /* Use VISUAL to open text files */
  209. uint runplugin : 1; /* Choose plugin mode */
  210. uint runctx : 2; /* The context in which plugin is to be run */
  211. uint filter_re : 1; /* Use regex filters */
  212. uint wild : 1; /* Do not sort entries on dir load */
  213. uint trash : 1; /* Move removed files to trash */
  214. } settings;
  215. /* Contexts or workspaces */
  216. typedef struct {
  217. char c_path[PATH_MAX]; /* Current dir */
  218. char c_last[PATH_MAX]; /* Last visited dir */
  219. char c_name[NAME_MAX + 1]; /* Current file name */
  220. char c_fltr[REGEX_MAX]; /* Current filter */
  221. settings c_cfg; /* Current configuration */
  222. uint color; /* Color code for directories */
  223. } context;
  224. /* GLOBALS */
  225. /* Configuration, contexts */
  226. static settings cfg = {
  227. 0, /* filtermode */
  228. 0, /* mtimeorder */
  229. 0, /* sizeorder */
  230. 0, /* apparentsz */
  231. 0, /* blkorder */
  232. 0, /* extnorder */
  233. 0, /* showhidden */
  234. 0, /* copymode */
  235. 0, /* showdetail */
  236. 1, /* ctxactive */
  237. 0, /* reserved */
  238. 0, /* curctx */
  239. 0, /* dircolor */
  240. 0, /* picker */
  241. 0, /* pickraw */
  242. 0, /* nonavopen */
  243. 1, /* autoselect */
  244. 0, /* metaviewer */
  245. 0, /* useeditor */
  246. 0, /* runplugin */
  247. 0, /* runctx */
  248. 1, /* filter_re */
  249. 0, /* wild */
  250. 0, /* trash */
  251. };
  252. static context g_ctx[CTX_MAX] __attribute__ ((aligned));
  253. static int ndents, cur, curscroll, total_dents = ENTRY_INCR;
  254. static int xlines, xcols;
  255. static uint idle;
  256. static uint idletimeout, copybufpos, copybuflen;
  257. static char *opener;
  258. static char *copier;
  259. static char *editor;
  260. static char *pager;
  261. static char *shell;
  262. static char *home;
  263. static char *initpath;
  264. static char *cfgdir;
  265. static char *g_cppath;
  266. static char *plugindir;
  267. static char *pnamebuf, *pcopybuf;
  268. static struct entry *dents;
  269. static blkcnt_t ent_blocks;
  270. static blkcnt_t dir_blocks;
  271. static ulong num_files;
  272. static bm bookmark[BM_MAX];
  273. static size_t g_tmpfplen;
  274. static uchar g_crc;
  275. static uchar BLK_SHIFT = 9;
  276. static bool interrupted = FALSE;
  277. /* Retain old signal handlers */
  278. #ifdef __linux__
  279. static sighandler_t oldsighup; /* old value of hangup signal */
  280. static sighandler_t oldsigtstp; /* old value of SIGTSTP */
  281. #else
  282. static sig_t oldsighup;
  283. static sig_t oldsigtstp;
  284. #endif
  285. /* For use in functions which are isolated and don't return the buffer */
  286. static char g_buf[CMD_LEN_MAX] __attribute__ ((aligned));
  287. /* Buffer to store tmp file path to show selection, file stats and help */
  288. static char g_tmpfpath[TMP_LEN_MAX] __attribute__ ((aligned));
  289. /* Replace-str for xargs on different platforms */
  290. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  291. #define REPLACE_STR 'J'
  292. #elif defined(__linux__) || defined(__CYGWIN__)
  293. #define REPLACE_STR 'I'
  294. #else
  295. #define REPLACE_STR 'I'
  296. #endif
  297. /* Options to identify file mime */
  298. #ifdef __APPLE__
  299. #define FILE_OPTS "-bIL"
  300. #else
  301. #define FILE_OPTS "-biL"
  302. #endif
  303. /* Macros for utilities */
  304. #define MEDIAINFO 0
  305. #define EXIFTOOL 1
  306. #define OPENER 2
  307. #define ATOOL 3
  308. #define BSDTAR 4
  309. #define UNZIP 5
  310. #define TAR 6
  311. #define LOCKER 7
  312. #define CMATRIX 8
  313. #define NLAUNCH 9
  314. #define UNKNOWN 10
  315. /* Utilities to open files, run actions */
  316. static char * const utils[] = {
  317. "mediainfo",
  318. "exiftool",
  319. #ifdef __APPLE__
  320. "/usr/bin/open",
  321. #elif defined __CYGWIN__
  322. "cygstart",
  323. #else
  324. "xdg-open",
  325. #endif
  326. "atool",
  327. "bsdtar",
  328. "unzip",
  329. "tar",
  330. #ifdef __APPLE__
  331. "bashlock",
  332. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
  333. "lock",
  334. #else
  335. "vlock",
  336. #endif
  337. "cmatrix",
  338. "nlaunch",
  339. "UNKNOWN"
  340. };
  341. #ifdef __linux__
  342. static char cp[] = "cpg -giRp";
  343. static char mv[] = "mvg -gi";
  344. #endif
  345. /* Common strings */
  346. #define STR_INPUT_ID 0
  347. #define STR_INVBM_KEY 1
  348. #define STR_DATE_ID 2
  349. #define STR_TMPFILE 3
  350. #define NONE_SELECTED 4
  351. #define UTIL_MISSING 5
  352. static const char * const messages[] = {
  353. "no traversal",
  354. "invalid key",
  355. "%F %T %z",
  356. "/.nnnXXXXXX",
  357. "empty selection",
  358. "utility missing",
  359. };
  360. /* Supported configuration environment variables */
  361. #define NNN_BMS 0
  362. #define NNN_OPENER 1
  363. #define NNN_CONTEXT_COLORS 2
  364. #define NNN_IDLE_TIMEOUT 3
  365. #define NNN_COPIER 4
  366. #define NNN_NOTE 5
  367. #define NNNLVL 6 /* strings end here */
  368. #define NNN_USE_EDITOR 7 /* flags begin here */
  369. #define NNN_NO_AUTOSELECT 8
  370. #define NNN_RESTRICT_NAV_OPEN 9
  371. #define NNN_TRASH 10
  372. #ifdef __linux__
  373. #define NNN_OPS_PROG 11
  374. #endif
  375. static const char * const env_cfg[] = {
  376. "NNN_BMS",
  377. "NNN_OPENER",
  378. "NNN_CONTEXT_COLORS",
  379. "NNN_IDLE_TIMEOUT",
  380. "NNN_COPIER",
  381. "NNN_NOTE",
  382. "NNNLVL",
  383. "NNN_USE_EDITOR",
  384. "NNN_NO_AUTOSELECT",
  385. "NNN_RESTRICT_NAV_OPEN",
  386. "NNN_TRASH",
  387. #ifdef __linux__
  388. "NNN_OPS_PROG",
  389. #endif
  390. };
  391. /* Required environment variables */
  392. #define SHELL 0
  393. #define VISUAL 1
  394. #define EDITOR 2
  395. #define PAGER 3
  396. static const char * const envs[] = {
  397. "SHELL",
  398. "VISUAL",
  399. "EDITOR",
  400. "PAGER",
  401. };
  402. /* Event handling */
  403. #ifdef LINUX_INOTIFY
  404. #define NUM_EVENT_SLOTS 16 /* Make room for 16 events */
  405. #define EVENT_SIZE (sizeof(struct inotify_event))
  406. #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
  407. static int inotify_fd, inotify_wd = -1;
  408. static uint INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
  409. | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  410. #elif defined(BSD_KQUEUE)
  411. #define NUM_EVENT_SLOTS 1
  412. #define NUM_EVENT_FDS 1
  413. static int kq, event_fd = -1;
  414. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  415. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
  416. | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  417. static struct timespec gtimeout;
  418. #endif
  419. /* Function macros */
  420. #define exitcurses() endwin()
  421. #define clearprompt() printmsg("")
  422. #define printwarn(presel) printwait(strerror(errno), presel)
  423. #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
  424. #define copycurname() xstrlcpy(lastname, dents[cur].name, NAME_MAX + 1)
  425. #define settimeout() timeout(1000)
  426. #define cleartimeout() timeout(-1)
  427. #define errexit() printerr(__LINE__)
  428. #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (dir_changed = TRUE))
  429. /* We don't care about the return value from strcmp() */
  430. #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
  431. /* A faster version of xisdigit */
  432. #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
  433. #define xerror() perror(xitoa(__LINE__))
  434. /* Forward declarations */
  435. static void redraw(char *path);
  436. static int spawn(char *file, char *arg1, char *arg2, const char *dir, uchar flag);
  437. static int (*nftw_fn)(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf);
  438. static int dentfind(const char *fname, int n);
  439. static void move_cursor(int target, int ignore_scrolloff);
  440. static bool getutil(const char *util);
  441. /* Functions */
  442. /*
  443. * CRC8 source:
  444. * https://barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code
  445. */
  446. static uchar crc8fast(const uchar * const message, size_t n)
  447. {
  448. uchar data, remainder = 0;
  449. size_t byte = 0;
  450. /* CRC data */
  451. static const uchar crc8table[CRC8_TABLE_LEN] __attribute__ ((aligned)) = {
  452. 0, 94, 188, 226, 97, 63, 221, 131, 194, 156, 126, 32, 163, 253, 31, 65,
  453. 157, 195, 33, 127, 252, 162, 64, 30, 95, 1, 227, 189, 62, 96, 130, 220,
  454. 35, 125, 159, 193, 66, 28, 254, 160, 225, 191, 93, 3, 128, 222, 60, 98,
  455. 190, 224, 2, 92, 223, 129, 99, 61, 124, 34, 192, 158, 29, 67, 161, 255,
  456. 70, 24, 250, 164, 39, 121, 155, 197, 132, 218, 56, 102, 229, 187, 89, 7,
  457. 219, 133, 103, 57, 186, 228, 6, 88, 25, 71, 165, 251, 120, 38, 196, 154,
  458. 101, 59, 217, 135, 4, 90, 184, 230, 167, 249, 27, 69, 198, 152, 122, 36,
  459. 248, 166, 68, 26, 153, 199, 37, 123, 58, 100, 134, 216, 91, 5, 231, 185,
  460. 140, 210, 48, 110, 237, 179, 81, 15, 78, 16, 242, 172, 47, 113, 147, 205,
  461. 17, 79, 173, 243, 112, 46, 204, 146, 211, 141, 111, 49, 178, 236, 14, 80,
  462. 175, 241, 19, 77, 206, 144, 114, 44, 109, 51, 209, 143, 12, 82, 176, 238,
  463. 50, 108, 142, 208, 83, 13, 239, 177, 240, 174, 76, 18, 145, 207, 45, 115,
  464. 202, 148, 118, 40, 171, 245, 23, 73, 8, 86, 180, 234, 105, 55, 213, 139,
  465. 87, 9, 235, 181, 54, 104, 138, 212, 149, 203, 41, 119, 244, 170, 72, 22,
  466. 233, 183, 85, 11, 136, 214, 52, 106, 43, 117, 151, 201, 74, 20, 246, 168,
  467. 116, 42, 200, 150, 21, 75, 169, 247, 182, 232, 10, 84, 215, 137, 107, 53,
  468. };
  469. /* Divide the message by the polynomial, a byte at a time */
  470. while (byte < n) {
  471. data = message[byte] ^ (remainder >> (UCHAR_BIT_WIDTH - 8));
  472. remainder = crc8table[data] ^ (remainder << 8);
  473. ++byte;
  474. }
  475. /* The final remainder is the CRC */
  476. return remainder;
  477. }
  478. static void sigint_handler(int sig)
  479. {
  480. interrupted = TRUE;
  481. }
  482. static uint xatoi(const char *str)
  483. {
  484. int val = 0;
  485. if (!str)
  486. return 0;
  487. while (xisdigit(*str)) {
  488. val = val * 10 + (*str - '0');
  489. ++str;
  490. }
  491. return val;
  492. }
  493. static char *xitoa(uint val)
  494. {
  495. static char ascbuf[32] = {0};
  496. int i;
  497. for (i = 30; val && i; --i, val /= 10)
  498. ascbuf[i] = '0' + (val % 10);
  499. return &ascbuf[++i];
  500. }
  501. /* Messages show up at the bottom */
  502. static inline void printmsg(const char *msg)
  503. {
  504. mvprintw(xlines - 1, 0, "%s\n", msg);
  505. }
  506. static void printwait(const char *msg, int *presel)
  507. {
  508. printmsg(msg);
  509. if (presel)
  510. *presel = MSGWAIT;
  511. }
  512. /* Kill curses and display error before exiting */
  513. static void printerr(int linenum)
  514. {
  515. exitcurses();
  516. perror(xitoa(linenum));
  517. if (!cfg.picker && g_cppath)
  518. unlink(g_cppath);
  519. free(pcopybuf);
  520. exit(1);
  521. }
  522. /* Print prompt on the last line */
  523. static void printprompt(const char *str)
  524. {
  525. clearprompt();
  526. printw(str);
  527. }
  528. static int get_input(const char *prompt)
  529. {
  530. int r;
  531. if (prompt)
  532. printprompt(prompt);
  533. cleartimeout();
  534. r = getch();
  535. settimeout();
  536. return r;
  537. }
  538. static void xdelay(void)
  539. {
  540. refresh();
  541. usleep(350000); /* 350 ms delay */
  542. }
  543. static char confirm_force(void)
  544. {
  545. int r = get_input("use force? [y/Y confirms]");
  546. if (r == 'y' || r == 'Y')
  547. return 'f'; /* forceful */
  548. return 'i'; /* interactive */
  549. }
  550. /* Increase the limit on open file descriptors, if possible */
  551. static rlim_t max_openfds(void)
  552. {
  553. struct rlimit rl;
  554. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  555. if (limit != 0)
  556. return 32;
  557. limit = rl.rlim_cur;
  558. rl.rlim_cur = rl.rlim_max;
  559. /* Return ~75% of max possible */
  560. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  561. limit = rl.rlim_max - (rl.rlim_max >> 2);
  562. /*
  563. * 20K is arbitrary. If the limit is set to max possible
  564. * value, the memory usage increases to more than double.
  565. */
  566. return limit > 20480 ? 20480 : limit;
  567. }
  568. return limit;
  569. }
  570. /*
  571. * Wrapper to realloc()
  572. * Frees current memory if realloc() fails and returns NULL.
  573. *
  574. * As per the docs, the *alloc() family is supposed to be memory aligned:
  575. * Ubuntu: http://manpages.ubuntu.com/manpages/xenial/man3/malloc.3.html
  576. * macOS: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/malloc.3.html
  577. */
  578. static void *xrealloc(void *pcur, size_t len)
  579. {
  580. void *pmem = realloc(pcur, len);
  581. if (!pmem)
  582. free(pcur);
  583. return pmem;
  584. }
  585. /*
  586. * Just a safe strncpy(3)
  587. * Always null ('\0') terminates if both src and dest are valid pointers.
  588. * Returns the number of bytes copied including terminating null byte.
  589. */
  590. static size_t xstrlcpy(char *dest, const char *src, size_t n)
  591. {
  592. if (!src || !dest || !n)
  593. return 0;
  594. ulong *s, *d;
  595. size_t len = strlen(src) + 1, blocks;
  596. const uint _WSHIFT = (LONG_SIZE == 8) ? 3 : 2;
  597. if (n > len)
  598. n = len;
  599. else if (len > n)
  600. /* Save total number of bytes to copy in len */
  601. len = n;
  602. /*
  603. * To enable -O3 ensure src and dest are 16-byte aligned
  604. * More info: http://www.felixcloutier.com/x86/MOVDQA.html
  605. */
  606. if ((n >= LONG_SIZE) && (((ulong)src & _ALIGNMENT_MASK) == 0 &&
  607. ((ulong)dest & _ALIGNMENT_MASK) == 0)) {
  608. s = (ulong *)src;
  609. d = (ulong *)dest;
  610. blocks = n >> _WSHIFT;
  611. n &= LONG_SIZE - 1;
  612. while (blocks) {
  613. *d = *s; // NOLINT
  614. ++d, ++s;
  615. --blocks;
  616. }
  617. if (!n) {
  618. dest = (char *)d;
  619. *--dest = '\0';
  620. return len;
  621. }
  622. src = (char *)s;
  623. dest = (char *)d;
  624. }
  625. while (--n && (*dest = *src)) // NOLINT
  626. ++dest, ++src;
  627. if (!n)
  628. *dest = '\0';
  629. return len;
  630. }
  631. static bool is_suffix(const char *str, const char *suffix)
  632. {
  633. if (!str || !suffix)
  634. return FALSE;
  635. size_t lenstr = strlen(str);
  636. size_t lensuffix = strlen(suffix);
  637. if (lensuffix > lenstr)
  638. return FALSE;
  639. return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
  640. }
  641. /*
  642. * The poor man's implementation of memrchr(3).
  643. * We are only looking for '/' in this program.
  644. * And we are NOT expecting a '/' at the end.
  645. * Ideally 0 < n <= strlen(s).
  646. */
  647. static void *xmemrchr(uchar *s, uchar ch, size_t n)
  648. {
  649. if (!s || !n)
  650. return NULL;
  651. uchar *ptr = s + n;
  652. do {
  653. --ptr;
  654. if (*ptr == ch)
  655. return ptr;
  656. } while (s != ptr);
  657. return NULL;
  658. }
  659. static char *xbasename(char *path)
  660. {
  661. char *base = xmemrchr((uchar *)path, '/', strlen(path)); // NOLINT
  662. return base ? base + 1 : path;
  663. }
  664. static int create_tmp_file()
  665. {
  666. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - g_tmpfplen);
  667. return mkstemp(g_tmpfpath);
  668. }
  669. /* Writes buflen char(s) from buf to a file */
  670. static void writecp(const char *buf, const size_t buflen)
  671. {
  672. if (cfg.pickraw || !g_cppath)
  673. return;
  674. FILE *fp = fopen(g_cppath, "w");
  675. if (fp) {
  676. if (fwrite(buf, 1, buflen, fp) != buflen)
  677. printwarn(NULL);
  678. fclose(fp);
  679. } else
  680. printwarn(NULL);
  681. }
  682. static void appendfpath(const char *path, const size_t len)
  683. {
  684. if ((copybufpos >= copybuflen) || ((len + 3) > (copybuflen - copybufpos))) {
  685. copybuflen += PATH_MAX;
  686. pcopybuf = xrealloc(pcopybuf, copybuflen);
  687. if (!pcopybuf)
  688. errexit();
  689. }
  690. copybufpos += xstrlcpy(pcopybuf + copybufpos, path, len);
  691. }
  692. /* Write selected file paths to fd, linefeed separated */
  693. static size_t selectiontofd(int fd, uint *pcount)
  694. {
  695. uint lastpos, count = 0;
  696. char *pbuf = pcopybuf;
  697. size_t pos = 0, len;
  698. ssize_t r;
  699. if (pcount)
  700. *pcount = 0;
  701. if (!copybufpos)
  702. return 0;
  703. lastpos = copybufpos - 1;
  704. while (pos <= lastpos) {
  705. len = strlen(pbuf);
  706. pos += len;
  707. r = write(fd, pbuf, len);
  708. if (r != (ssize_t)len)
  709. return pos;
  710. if (pos <= lastpos) {
  711. if (write(fd, "\n", 1) != 1)
  712. return pos;
  713. pbuf += len + 1;
  714. }
  715. ++pos;
  716. ++count;
  717. }
  718. if (pcount)
  719. *pcount = count;
  720. return pos;
  721. }
  722. /* List selection from selection buffer */
  723. static bool showcplist(void)
  724. {
  725. int fd;
  726. size_t pos;
  727. if (!copybufpos)
  728. return FALSE;
  729. fd = create_tmp_file();
  730. if (fd == -1) {
  731. DPRINTF_S("mkstemp failed!");
  732. return FALSE;
  733. }
  734. pos = selectiontofd(fd, NULL);
  735. close(fd);
  736. if (pos && pos == copybufpos)
  737. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  738. unlink(g_tmpfpath);
  739. return TRUE;
  740. }
  741. /* List selection from selection file (another instance) */
  742. static bool showcpfile(void)
  743. {
  744. struct stat sb;
  745. if (stat(g_cppath, &sb) == -1)
  746. return FALSE;
  747. /* Nothing selected if file size is 0 */
  748. if (!sb.st_size)
  749. return FALSE;
  750. snprintf(g_buf, CMD_LEN_MAX, "cat %s | tr \'\\0\' \'\\n\'", g_cppath);
  751. spawn("sh", "-c", g_buf, NULL, F_NORMAL | F_CMD);
  752. return TRUE;
  753. }
  754. static bool cpsafe(void)
  755. {
  756. /* Fail if selection file path not generated */
  757. if (!g_cppath) {
  758. printmsg("selection file not found");
  759. return FALSE;
  760. }
  761. /* Warn if selection not completed */
  762. if (cfg.copymode) {
  763. printmsg("finish selection first");
  764. return FALSE;
  765. }
  766. /* Fail if selection file path isn't accessible */
  767. if (access(g_cppath, R_OK | W_OK) == -1) {
  768. errno == ENOENT ? printmsg(messages[NONE_SELECTED]) : printwarn(NULL);
  769. return FALSE;
  770. }
  771. return TRUE;
  772. }
  773. /* Reset copy indicators */
  774. static void resetcpind(void)
  775. {
  776. int r = 0;
  777. /* Reset copy indicators */
  778. for (; r < ndents; ++r)
  779. if (dents[r].flags & FILE_COPIED)
  780. dents[r].flags &= ~FILE_COPIED;
  781. }
  782. /* Initialize curses mode */
  783. static bool initcurses(void)
  784. {
  785. short i;
  786. if (cfg.picker) {
  787. if (!newterm(NULL, stderr, stdin)) {
  788. fprintf(stderr, "newterm!\n");
  789. return FALSE;
  790. }
  791. } else if (!initscr()) {
  792. char *term = getenv("TERM");
  793. if (term)
  794. fprintf(stderr, "error opening TERM: %s\n", term);
  795. else
  796. fprintf(stderr, "initscr!\n");
  797. return FALSE;
  798. }
  799. cbreak();
  800. noecho();
  801. nonl();
  802. //intrflush(stdscr, FALSE);
  803. keypad(stdscr, TRUE);
  804. #if NCURSES_MOUSE_VERSION <= 1
  805. mousemask(BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED, NULL);
  806. #else
  807. mousemask(BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED | BUTTON4_PRESSED | BUTTON5_PRESSED, NULL);
  808. #endif
  809. mouseinterval(400);
  810. curs_set(FALSE); /* Hide cursor */
  811. start_color();
  812. use_default_colors();
  813. /* Initialize default colors */
  814. for (i = 0; i < CTX_MAX; ++i)
  815. init_pair(i + 1, g_ctx[i].color, -1);
  816. settimeout(); /* One second */
  817. set_escdelay(25);
  818. return TRUE;
  819. }
  820. /* No NULL check here as spawn() guards against it */
  821. static int parseargs(char *line, char **argv)
  822. {
  823. int count = 0;
  824. argv[count++] = line;
  825. while (*line) { // NOLINT
  826. if (ISBLANK(*line)) {
  827. *line++ = '\0';
  828. if (!*line) // NOLINT
  829. return count;
  830. argv[count++] = line;
  831. if (count == EXEC_ARGS_MAX)
  832. return -1;
  833. }
  834. ++line;
  835. }
  836. return count;
  837. }
  838. static pid_t xfork(uchar flag)
  839. {
  840. pid_t p = fork();
  841. if (p > 0) {
  842. /* the parent ignores the interrupt, quit and hangup signals */
  843. oldsighup = signal(SIGHUP, SIG_IGN);
  844. oldsigtstp = signal(SIGTSTP, SIG_DFL);
  845. } else if (p == 0) {
  846. /* so they can be used to stop the child */
  847. signal(SIGHUP, SIG_DFL);
  848. signal(SIGINT, SIG_DFL);
  849. signal(SIGQUIT, SIG_DFL);
  850. signal(SIGTSTP, SIG_DFL);
  851. if (flag & F_NOWAIT)
  852. setsid();
  853. }
  854. if (p == -1)
  855. perror("fork");
  856. return p;
  857. }
  858. static int join(pid_t p, uchar flag)
  859. {
  860. int status = 0xFFFF;
  861. if (!(flag & F_NOWAIT)) {
  862. /* wait for the child to exit */
  863. do {
  864. } while (waitpid(p, &status, 0) == -1);
  865. if (WIFEXITED(status)) {
  866. status = WEXITSTATUS(status);
  867. DPRINTF_D(status);
  868. }
  869. }
  870. /* restore parent's signal handling */
  871. signal(SIGHUP, oldsighup);
  872. signal(SIGTSTP, oldsigtstp);
  873. return status;
  874. }
  875. /*
  876. * Spawns a child process. Behaviour can be controlled using flag.
  877. * Limited to 2 arguments to a program, flag works on bit set.
  878. */
  879. static int spawn(char *file, char *arg1, char *arg2, const char *dir, uchar flag)
  880. {
  881. pid_t pid;
  882. int status, retstatus = 0xFFFF;
  883. char *argv[EXEC_ARGS_MAX] = {0};
  884. char *cmd = NULL;
  885. if (!file || !*file)
  886. return retstatus;
  887. /* Swap args if the first arg is NULL and second isn't */
  888. if (!arg1 && arg2) {
  889. arg1 = arg2;
  890. arg2 = NULL;
  891. }
  892. if (flag & F_MULTI) {
  893. size_t len = strlen(file) + 1;
  894. cmd = (char *)malloc(len);
  895. if (!cmd) {
  896. DPRINTF_S("malloc()!");
  897. return retstatus;
  898. }
  899. xstrlcpy(cmd, file, len);
  900. status = parseargs(cmd, argv);
  901. if (status == -1 || status > (EXEC_ARGS_MAX - 3)) { /* arg1, arg2 and last NULL */
  902. free(cmd);
  903. DPRINTF_S("NULL or too many args");
  904. return retstatus;
  905. }
  906. argv[status++] = arg1;
  907. argv[status] = arg2;
  908. } else {
  909. argv[0] = file;
  910. argv[1] = arg1;
  911. argv[2] = arg2;
  912. }
  913. if (flag & F_NORMAL)
  914. exitcurses();
  915. pid = xfork(flag);
  916. if (pid == 0) {
  917. if (dir && chdir(dir) == -1)
  918. _exit(1);
  919. /* Suppress stdout and stderr */
  920. if (flag & F_NOTRACE) {
  921. int fd = open("/dev/null", O_WRONLY, 0200);
  922. dup2(fd, 1);
  923. dup2(fd, 2);
  924. close(fd);
  925. }
  926. execvp(*argv, argv);
  927. _exit(1);
  928. } else {
  929. retstatus = join(pid, flag);
  930. DPRINTF_D(pid);
  931. if (flag & F_NORMAL) {
  932. if (flag & F_CMD) {
  933. printf("\nPress Enter to continue");
  934. getchar();
  935. }
  936. refresh();
  937. }
  938. free(cmd);
  939. }
  940. return retstatus;
  941. }
  942. /* Get program name from env var, else return fallback program */
  943. static char *xgetenv(const char *name, char *fallback)
  944. {
  945. char *value = getenv(name);
  946. return value && value[0] ? value : fallback;
  947. }
  948. /* Checks if an env variable is set to 1 */
  949. static bool xgetenv_set(const char *name)
  950. {
  951. char *value = getenv(name);
  952. if (value && value[0] == '1' && !value[1])
  953. return TRUE;
  954. return FALSE;
  955. }
  956. /* Check if a dir exists, IS a dir and is readable */
  957. static bool xdiraccess(const char *path)
  958. {
  959. DIR *dirp = opendir(path);
  960. if (!dirp) {
  961. printwarn(NULL);
  962. return FALSE;
  963. }
  964. closedir(dirp);
  965. return TRUE;
  966. }
  967. static void cpstr(char *buf)
  968. {
  969. snprintf(buf, CMD_LEN_MAX,
  970. #ifdef __linux__
  971. "xargs -0 -a %s -%c src %s src .", g_cppath, REPLACE_STR, cp);
  972. #else
  973. "cat %s | xargs -0 -o -%c src cp -iRp src .", g_cppath, REPLACE_STR);
  974. #endif
  975. }
  976. static void mvstr(char *buf)
  977. {
  978. snprintf(buf, CMD_LEN_MAX,
  979. #ifdef __linux__
  980. "xargs -0 -a %s -%c src %s src .", g_cppath, REPLACE_STR, mv);
  981. #else
  982. "cat %s | xargs -0 -o -%c src mv -i src .", g_cppath, REPLACE_STR);
  983. #endif
  984. }
  985. static void rmmulstr(char *buf)
  986. {
  987. if (cfg.trash) {
  988. snprintf(buf, CMD_LEN_MAX,
  989. #ifdef __linux__
  990. "xargs -0 -a %s trash-put", g_cppath);
  991. #else
  992. "cat %s | xargs -0 trash-put", g_cppath);
  993. #endif
  994. } else {
  995. snprintf(buf, CMD_LEN_MAX,
  996. #ifdef __linux__
  997. "xargs -0 -a %s rm -%cr", g_cppath, confirm_force());
  998. #else
  999. "cat %s | xargs -0 -o rm -%cr", g_cppath, confirm_force());
  1000. #endif
  1001. }
  1002. }
  1003. static void xrm(char *path)
  1004. {
  1005. if (cfg.trash)
  1006. spawn("trash-put", path, NULL, NULL, F_NORMAL);
  1007. else {
  1008. char rm_opts[] = "-ir";
  1009. rm_opts[1] = confirm_force();
  1010. spawn("rm", rm_opts, path, NULL, F_NORMAL);
  1011. }
  1012. }
  1013. static bool batch_rename(const char *path)
  1014. {
  1015. int fd1, fd2, i;
  1016. uint count = 0, lines = 0;
  1017. bool dir = FALSE, ret = FALSE;
  1018. const char renamecmd[] = "paste -d'\n' %s %s | tr '\n' '\\0' | xargs -0 -n2 mv 2>/dev/null";
  1019. char foriginal[TMP_LEN_MAX] = {0};
  1020. char buf[sizeof(renamecmd) + (PATH_MAX << 1)];
  1021. if ((fd1 = create_tmp_file()) == -1)
  1022. return ret;
  1023. xstrlcpy(foriginal, g_tmpfpath, strlen(g_tmpfpath)+1);
  1024. if ((fd2 = create_tmp_file()) == -1) {
  1025. unlink(foriginal);
  1026. close(fd1);
  1027. return ret;
  1028. }
  1029. if (!copybufpos) {
  1030. if (!ndents)
  1031. return TRUE;
  1032. for (i = 0; i < ndents; ++i)
  1033. appendfpath(dents[i].name, NAME_MAX);
  1034. dir = TRUE;
  1035. }
  1036. selectiontofd(fd1, &count);
  1037. selectiontofd(fd2, NULL);
  1038. close(fd2);
  1039. if (dir)
  1040. copybufpos = 0;
  1041. spawn(editor, g_tmpfpath, NULL, path, F_CLI);
  1042. /* Reopen file descriptor to get updated contents */
  1043. if ((fd2 = open(g_tmpfpath, O_RDONLY)) == -1)
  1044. goto finish;
  1045. while ((i = read(fd2, buf, sizeof(buf))) > 0) {
  1046. while (i)
  1047. lines += (buf[--i] == '\n');
  1048. }
  1049. if (i < 0)
  1050. goto finish;
  1051. DPRINTF_U(count);
  1052. DPRINTF_U(lines);
  1053. if (count != lines) {
  1054. DPRINTF_S("cannot delete files");
  1055. goto finish;
  1056. }
  1057. snprintf(buf, sizeof(buf), renamecmd, foriginal, g_tmpfpath);
  1058. spawn("sh", "-c", buf, path, F_NORMAL);
  1059. ret = TRUE;
  1060. finish:
  1061. if (fd1 >= 0)
  1062. close(fd1);
  1063. unlink(foriginal);
  1064. if (fd2 >= 0)
  1065. close(fd2);
  1066. unlink(g_tmpfpath);
  1067. return ret;
  1068. }
  1069. static void get_archive_cmd(char *cmd, char *archive)
  1070. {
  1071. if (getutil(utils[ATOOL]))
  1072. xstrlcpy(cmd, "atool -a", ARCHIVE_CMD_LEN);
  1073. else if (getutil(utils[BSDTAR]))
  1074. xstrlcpy(cmd, "bsdtar -cvf", ARCHIVE_CMD_LEN);
  1075. else if (is_suffix(archive, ".zip"))
  1076. xstrlcpy(cmd, "zip -r", ARCHIVE_CMD_LEN);
  1077. else
  1078. xstrlcpy(cmd, "tar -cvf", ARCHIVE_CMD_LEN);
  1079. }
  1080. static void archive_selection(const char *cmd, const char *archive, const char *curpath)
  1081. {
  1082. char *buf = (char *)malloc(CMD_LEN_MAX * sizeof(char));
  1083. snprintf(buf, CMD_LEN_MAX,
  1084. #ifdef __linux__
  1085. "xargs -0 -a %s %s %s", g_cppath, cmd, archive);
  1086. #else
  1087. "cat %s | xargs -0 -o %s %s", g_cppath, cmd, archive);
  1088. #endif
  1089. spawn("sh", "-c", buf, curpath, F_NORMAL);
  1090. free(buf);
  1091. }
  1092. static bool write_lastdir(const char *curpath)
  1093. {
  1094. bool ret = TRUE;
  1095. size_t len = strlen(cfgdir);
  1096. xstrlcpy(cfgdir + len, "/.lastd", 8);
  1097. DPRINTF_S(cfgdir);
  1098. FILE *fp = fopen(cfgdir, "w");
  1099. if (fp) {
  1100. if (fprintf(fp, "cd \"%s\"", curpath) < 0)
  1101. ret = FALSE;
  1102. fclose(fp);
  1103. } else
  1104. ret = FALSE;
  1105. return ret;
  1106. }
  1107. static int digit_compare(const char *a, const char *b)
  1108. {
  1109. while (*a && *b && *a == *b)
  1110. ++a, ++b;
  1111. return *a - *b;
  1112. }
  1113. /*
  1114. * We assume none of the strings are NULL.
  1115. *
  1116. * Let's have the logic to sort numeric names in numeric order.
  1117. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  1118. *
  1119. * If the absolute numeric values are same, we fallback to alphasort.
  1120. */
  1121. static int xstricmp(const char * const s1, const char * const s2)
  1122. {
  1123. const char *c1 = s1, *c2 = s2, *m1, *m2;
  1124. int count1 = 0, count2 = 0, bias;
  1125. char sign[2] = {'+', '+'};
  1126. while (ISBLANK(*c1))
  1127. ++c1;
  1128. while (ISBLANK(*c2))
  1129. ++c2;
  1130. if (*c1 == '-' || *c1 == '+') {
  1131. if (*c1 == '-')
  1132. sign[0] = '-';
  1133. ++c1;
  1134. }
  1135. if (*c2 == '-' || *c2 == '+') {
  1136. if (*c2 == '-')
  1137. sign[1] = '-';
  1138. ++c2;
  1139. }
  1140. if (xisdigit(*c1) && xisdigit(*c2)) {
  1141. while (*c1 == '0')
  1142. ++c1;
  1143. m1 = c1;
  1144. while (*c2 == '0')
  1145. ++c2;
  1146. m2 = c2;
  1147. while (xisdigit(*c1)) {
  1148. ++count1;
  1149. ++c1;
  1150. }
  1151. while (ISBLANK(*c1))
  1152. ++c1;
  1153. while (xisdigit(*c2)) {
  1154. ++count2;
  1155. ++c2;
  1156. }
  1157. while (ISBLANK(*c2))
  1158. ++c2;
  1159. if (*c1 && !*c2)
  1160. return 1;
  1161. if (!*c1 && *c2)
  1162. return -1;
  1163. if (!*c1 && !*c2) {
  1164. if (sign[0] != sign[1])
  1165. return ((sign[0] == '+') ? 1 : -1);
  1166. if (count1 > count2)
  1167. return 1;
  1168. if (count1 < count2)
  1169. return -1;
  1170. bias = digit_compare(m1, m2);
  1171. if (bias)
  1172. return bias;
  1173. }
  1174. }
  1175. return strcoll(s1, s2);
  1176. }
  1177. /*
  1178. * Version comparison
  1179. *
  1180. * The code for version compare is a modified version of the GLIBC
  1181. * and uClibc implementation of strverscmp(). The source is here:
  1182. * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
  1183. */
  1184. /*
  1185. * Compare S1 and S2 as strings holding indices/version numbers,
  1186. * returning less than, equal to or greater than zero if S1 is less than,
  1187. * equal to or greater than S2 (for more info, see the texinfo doc).
  1188. *
  1189. * Ignores case.
  1190. */
  1191. static int xstrverscasecmp(const char * const s1, const char * const s2)
  1192. {
  1193. const uchar *p1 = (const uchar *)s1;
  1194. const uchar *p2 = (const uchar *)s2;
  1195. uchar c1, c2;
  1196. int state, diff;
  1197. /*
  1198. * Symbol(s) 0 [1-9] others
  1199. * Transition (10) 0 (01) d (00) x
  1200. */
  1201. static const uint8_t next_state[] = {
  1202. /* state x d 0 */
  1203. /* S_N */ S_N, S_I, S_Z,
  1204. /* S_I */ S_N, S_I, S_I,
  1205. /* S_F */ S_N, S_F, S_F,
  1206. /* S_Z */ S_N, S_F, S_Z
  1207. };
  1208. static const int8_t result_type[] __attribute__ ((aligned)) = {
  1209. /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
  1210. /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
  1211. /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
  1212. /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
  1213. /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
  1214. };
  1215. if (p1 == p2)
  1216. return 0;
  1217. c1 = TOUPPER(*p1);
  1218. ++p1;
  1219. c2 = TOUPPER(*p2);
  1220. ++p2;
  1221. /* Hint: '0' is a digit too. */
  1222. state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
  1223. while ((diff = c1 - c2) == 0) {
  1224. if (c1 == '\0')
  1225. return diff;
  1226. state = next_state[state];
  1227. c1 = TOUPPER(*p1);
  1228. ++p1;
  1229. c2 = TOUPPER(*p2);
  1230. ++p2;
  1231. state += (c1 == '0') + (xisdigit(c1) != 0);
  1232. }
  1233. state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))];
  1234. switch (state) {
  1235. case VCMP:
  1236. return diff;
  1237. case VLEN:
  1238. while (xisdigit(*p1++))
  1239. if (!xisdigit(*p2++))
  1240. return 1;
  1241. return xisdigit(*p2) ? -1 : diff;
  1242. default:
  1243. return state;
  1244. }
  1245. }
  1246. static int (*cmpfn)(const char * const s1, const char * const s2) = &xstricmp;
  1247. /* Return the integer value of a char representing HEX */
  1248. static char xchartohex(char c)
  1249. {
  1250. if (xisdigit(c))
  1251. return c - '0';
  1252. c = TOUPPER(c);
  1253. if (c >= 'A' && c <= 'F')
  1254. return c - 'A' + 10;
  1255. return c;
  1256. }
  1257. static int setfilter(regex_t *regex, const char *filter)
  1258. {
  1259. int r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  1260. if (r != 0 && filter && filter[0] != '\0')
  1261. mvprintw(xlines - 1, 0, "regex error: %d\n", r);
  1262. return r;
  1263. }
  1264. static int visible_re(regex_t *regex, const char *fname, const char *fltr)
  1265. {
  1266. return regexec(regex, fname, 0, NULL, 0) == 0;
  1267. }
  1268. static int visible_str(regex_t *regex, const char *fname, const char *fltr)
  1269. {
  1270. return strcasestr(fname, fltr) != NULL;
  1271. }
  1272. static int (*filterfn)(regex_t *regex, const char *fname, const char *fltr) = &visible_re;
  1273. static int entrycmp(const void *va, const void *vb)
  1274. {
  1275. const struct entry *pa = (pEntry)va;
  1276. const struct entry *pb = (pEntry)vb;
  1277. if ((pb->flags & DIR_OR_LINK_TO_DIR) != (pa->flags & DIR_OR_LINK_TO_DIR)) {
  1278. if (pb->flags & DIR_OR_LINK_TO_DIR)
  1279. return 1;
  1280. return -1;
  1281. }
  1282. /* Sort based on specified order */
  1283. if (cfg.mtimeorder) {
  1284. if (pb->t > pa->t)
  1285. return 1;
  1286. if (pb->t < pa->t)
  1287. return -1;
  1288. } else if (cfg.sizeorder) {
  1289. if (pb->size > pa->size)
  1290. return 1;
  1291. if (pb->size < pa->size)
  1292. return -1;
  1293. } else if (cfg.blkorder) {
  1294. if (pb->blocks > pa->blocks)
  1295. return 1;
  1296. if (pb->blocks < pa->blocks)
  1297. return -1;
  1298. } else if (cfg.extnorder && !(pb->flags & DIR_OR_LINK_TO_DIR)) {
  1299. char *extna = xmemrchr((uchar *)pa->name, '.', strlen(pa->name));
  1300. char *extnb = xmemrchr((uchar *)pb->name, '.', strlen(pb->name));
  1301. if (extna || extnb) {
  1302. if (!extna)
  1303. return 1;
  1304. if (!extnb)
  1305. return -1;
  1306. int ret = strcasecmp(extna, extnb);
  1307. if (ret)
  1308. return ret;
  1309. }
  1310. }
  1311. return cmpfn(pa->name, pb->name);
  1312. }
  1313. /*
  1314. * Returns SEL_* if key is bound and 0 otherwise.
  1315. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  1316. * The next keyboard input can be simulated by presel.
  1317. */
  1318. static int nextsel(int presel)
  1319. {
  1320. int c = presel;
  1321. uint i;
  1322. const uint len = LEN(bindings);
  1323. #ifdef LINUX_INOTIFY
  1324. struct inotify_event *event;
  1325. char inotify_buf[EVENT_BUF_LEN];
  1326. memset((void *)inotify_buf, 0x0, EVENT_BUF_LEN);
  1327. #elif defined(BSD_KQUEUE)
  1328. struct kevent event_data[NUM_EVENT_SLOTS];
  1329. memset((void *)event_data, 0x0, sizeof(struct kevent) * NUM_EVENT_SLOTS);
  1330. #endif
  1331. if (c == 0 || c == MSGWAIT) {
  1332. c = getch();
  1333. DPRINTF_D(c);
  1334. if (presel == MSGWAIT) {
  1335. if (cfg.filtermode)
  1336. c = FILTER;
  1337. else
  1338. c = CONTROL('L');
  1339. }
  1340. }
  1341. if (c == -1) {
  1342. ++idle;
  1343. /*
  1344. * Do not check for directory changes in du mode.
  1345. * A redraw forces du calculation.
  1346. * Check for changes every odd second.
  1347. */
  1348. #ifdef LINUX_INOTIFY
  1349. if (!cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
  1350. i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
  1351. if (i > 0) {
  1352. char *ptr;
  1353. for (ptr = inotify_buf;
  1354. ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
  1355. ptr += sizeof(struct inotify_event) + event->len) {
  1356. event = (struct inotify_event *) ptr;
  1357. DPRINTF_D(event->wd);
  1358. DPRINTF_D(event->mask);
  1359. if (!event->wd)
  1360. break;
  1361. if (event->mask & INOTIFY_MASK) {
  1362. c = CONTROL('L');
  1363. DPRINTF_S("issue refresh");
  1364. break;
  1365. }
  1366. }
  1367. DPRINTF_S("inotify read done");
  1368. }
  1369. }
  1370. #elif defined(BSD_KQUEUE)
  1371. if (!cfg.blkorder && event_fd >= 0 && idle & 1
  1372. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
  1373. event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  1374. c = CONTROL('L');
  1375. #endif
  1376. } else
  1377. idle = 0;
  1378. for (i = 0; i < len; ++i)
  1379. if (c == bindings[i].sym)
  1380. return bindings[i].act;
  1381. return 0;
  1382. }
  1383. static inline void swap_ent(int id1, int id2)
  1384. {
  1385. struct entry _dent, *pdent1 = &dents[id1], *pdent2 = &dents[id2];
  1386. *(&_dent) = *pdent1;
  1387. *pdent1 = *pdent2;
  1388. *pdent2 = *(&_dent);
  1389. }
  1390. /*
  1391. * Move non-matching entries to the end
  1392. */
  1393. static int fill(const char *fltr, regex_t *re)
  1394. {
  1395. int count = 0;
  1396. for (; count < ndents; ++count) {
  1397. if (filterfn(re, dents[count].name, fltr) == 0) {
  1398. if (count != --ndents) {
  1399. swap_ent(count, ndents);
  1400. --count;
  1401. }
  1402. continue;
  1403. }
  1404. }
  1405. return ndents;
  1406. }
  1407. static int matches(const char *fltr)
  1408. {
  1409. regex_t re;
  1410. /* Search filter */
  1411. if (cfg.filter_re && setfilter(&re, fltr) != 0)
  1412. return -1;
  1413. ndents = fill(fltr, &re);
  1414. if (cfg.filter_re)
  1415. regfree(&re);
  1416. if (!ndents)
  1417. return 0;
  1418. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1419. return 0;
  1420. }
  1421. static int filterentries(char *path)
  1422. {
  1423. wchar_t *wln = (wchar_t *)alloca(sizeof(wchar_t) * REGEX_MAX);
  1424. char *ln = g_ctx[cfg.curctx].c_fltr;
  1425. wint_t ch[2] = {0};
  1426. int r, total = ndents, oldcur = cur, len;
  1427. char *pln = g_ctx[cfg.curctx].c_fltr + 1;
  1428. cur = 0;
  1429. if (ndents && ln[0] == FILTER && *pln) {
  1430. if (matches(pln) != -1)
  1431. redraw(path);
  1432. len = mbstowcs(wln, ln, REGEX_MAX);
  1433. } else {
  1434. ln[0] = wln[0] = FILTER;
  1435. ln[1] = wln[1] = '\0';
  1436. len = 1;
  1437. }
  1438. cleartimeout();
  1439. curs_set(TRUE);
  1440. printprompt(ln);
  1441. while ((r = get_wch(ch)) != ERR) {
  1442. switch (*ch) {
  1443. case KEY_DC: // fallthrough
  1444. case KEY_BACKSPACE: // fallthrough
  1445. case '\b': // fallthrough
  1446. case CONTROL('L'): // fallthrough
  1447. case 127: /* handle DEL */
  1448. if (len == 1 && *ch != CONTROL('L')) {
  1449. cur = oldcur;
  1450. *ch = CONTROL('L');
  1451. goto end;
  1452. }
  1453. if (*ch == CONTROL('L'))
  1454. while (len > 1)
  1455. wln[--len] = '\0';
  1456. else
  1457. wln[--len] = '\0';
  1458. if (len == 1)
  1459. cur = oldcur;
  1460. wcstombs(ln, wln, REGEX_MAX);
  1461. ndents = total;
  1462. if (matches(pln) != -1)
  1463. redraw(path);
  1464. printprompt(ln);
  1465. continue;
  1466. case KEY_MOUSE: // fallthrough
  1467. case 27: /* Exit filter mode on Escape */
  1468. if (len == 1)
  1469. cur = oldcur;
  1470. goto end;
  1471. }
  1472. if (r == OK) {
  1473. /* Handle all control chars in main loop */
  1474. if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^') {
  1475. if (len == 1)
  1476. cur = oldcur;
  1477. goto end;
  1478. }
  1479. switch (*ch) {
  1480. case '\r': /* with nonl(), this is ENTER key value */
  1481. if (len == 1) {
  1482. cur = oldcur;
  1483. goto end;
  1484. }
  1485. if (matches(pln) == -1)
  1486. goto end;
  1487. redraw(path);
  1488. goto end;
  1489. case '/': /* works as Leader key in filter mode */
  1490. *ch = CONTROL('_'); // fallthrough
  1491. if (len == 1)
  1492. cur = oldcur;
  1493. goto end;
  1494. case '?': /* '?' is an invalid regex, show help instead */
  1495. if (len == 1) {
  1496. cur = oldcur;
  1497. goto end;
  1498. } // fallthrough
  1499. default:
  1500. /* Reset cur in case it's a repeat search */
  1501. if (len == 1)
  1502. cur = 0;
  1503. if (len == REGEX_MAX - 1)
  1504. break;
  1505. wln[len] = (wchar_t)*ch;
  1506. wln[++len] = '\0';
  1507. wcstombs(ln, wln, REGEX_MAX);
  1508. /* Forward-filtering optimization:
  1509. * - new matches can only be a subset of current matches.
  1510. */
  1511. /* ndents = total; */
  1512. if (matches(pln) == -1)
  1513. continue;
  1514. /* If the only match is a dir, auto-select and cd into it */
  1515. if (ndents == 1 && cfg.filtermode
  1516. && cfg.autoselect && S_ISDIR(dents[0].mode)) {
  1517. *ch = KEY_ENTER;
  1518. cur = 0;
  1519. goto end;
  1520. }
  1521. /*
  1522. * redraw() should be above the auto-select optimization, for
  1523. * the case where there's an issue with dir auto-select, say,
  1524. * due to a permission problem. The transition is _jumpy_ in
  1525. * case of such an error. However, we optimize for successful
  1526. * cases where the dir has permissions. This skips a redraw().
  1527. */
  1528. redraw(path);
  1529. printprompt(ln);
  1530. }
  1531. } else {
  1532. if (len == 1)
  1533. cur = oldcur;
  1534. goto end;
  1535. }
  1536. }
  1537. end:
  1538. if (*ch != '\t')
  1539. g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
  1540. move_cursor(cur, 0);
  1541. curs_set(FALSE);
  1542. settimeout();
  1543. /* Return keys for navigation etc. */
  1544. return *ch;
  1545. }
  1546. /* Show a prompt with input string and return the changes */
  1547. static char *xreadline(char *prefill, char *prompt)
  1548. {
  1549. size_t len, pos;
  1550. int x, y, r;
  1551. const int WCHAR_T_WIDTH = sizeof(wchar_t);
  1552. wint_t ch[2] = {0};
  1553. wchar_t * const buf = malloc(sizeof(wchar_t) * CMD_LEN_MAX);
  1554. if (!buf)
  1555. errexit();
  1556. cleartimeout();
  1557. printprompt(prompt);
  1558. if (prefill) {
  1559. DPRINTF_S(prefill);
  1560. len = pos = mbstowcs(buf, prefill, CMD_LEN_MAX);
  1561. } else
  1562. len = (size_t)-1;
  1563. if (len == (size_t)-1) {
  1564. buf[0] = '\0';
  1565. len = pos = 0;
  1566. }
  1567. getyx(stdscr, y, x);
  1568. curs_set(TRUE);
  1569. while (1) {
  1570. buf[len] = ' ';
  1571. mvaddnwstr(y, x, buf, len + 1);
  1572. move(y, x + wcswidth(buf, pos));
  1573. r = get_wch(ch);
  1574. if (r != ERR) {
  1575. if (r == OK) {
  1576. switch (*ch) {
  1577. case KEY_ENTER: // fallthrough
  1578. case '\n': // fallthrough
  1579. case '\r':
  1580. goto END;
  1581. case 127: // fallthrough
  1582. case '\b': /* rhel25 sends '\b' for backspace */
  1583. if (pos > 0) {
  1584. memmove(buf + pos - 1, buf + pos,
  1585. (len - pos) * WCHAR_T_WIDTH);
  1586. --len, --pos;
  1587. } // fallthrough
  1588. case '\t': /* TAB breaks cursor position, ignore it */
  1589. continue;
  1590. case CONTROL('L'):
  1591. printprompt(prompt);
  1592. len = pos = 0;
  1593. continue;
  1594. case CONTROL('A'):
  1595. pos = 0;
  1596. continue;
  1597. case CONTROL('E'):
  1598. pos = len;
  1599. continue;
  1600. case CONTROL('U'):
  1601. printprompt(prompt);
  1602. memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
  1603. len -= pos;
  1604. pos = 0;
  1605. continue;
  1606. case 27: /* Exit prompt on Escape */
  1607. len = 0;
  1608. goto END;
  1609. }
  1610. /* Filter out all other control chars */
  1611. if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
  1612. continue;
  1613. if (pos < CMD_LEN_MAX - 1) {
  1614. memmove(buf + pos + 1, buf + pos,
  1615. (len - pos) * WCHAR_T_WIDTH);
  1616. buf[pos] = *ch;
  1617. ++len, ++pos;
  1618. continue;
  1619. }
  1620. } else {
  1621. switch (*ch) {
  1622. case KEY_LEFT:
  1623. if (pos > 0)
  1624. --pos;
  1625. break;
  1626. case KEY_RIGHT:
  1627. if (pos < len)
  1628. ++pos;
  1629. break;
  1630. case KEY_BACKSPACE:
  1631. if (pos > 0) {
  1632. memmove(buf + pos - 1, buf + pos,
  1633. (len - pos) * WCHAR_T_WIDTH);
  1634. --len, --pos;
  1635. }
  1636. break;
  1637. case KEY_DC:
  1638. if (pos < len) {
  1639. memmove(buf + pos, buf + pos + 1,
  1640. (len - pos - 1) * WCHAR_T_WIDTH);
  1641. --len;
  1642. }
  1643. break;
  1644. case KEY_END:
  1645. pos = len;
  1646. break;
  1647. case KEY_HOME:
  1648. pos = 0;
  1649. break;
  1650. default:
  1651. break;
  1652. }
  1653. }
  1654. }
  1655. }
  1656. END:
  1657. curs_set(FALSE);
  1658. settimeout();
  1659. clearprompt();
  1660. buf[len] = '\0';
  1661. pos = wcstombs(g_buf, buf, CMD_LEN_MAX - 1);
  1662. if (pos >= CMD_LEN_MAX - 1)
  1663. g_buf[CMD_LEN_MAX - 1] = '\0';
  1664. free(buf);
  1665. return g_buf;
  1666. }
  1667. #ifndef NORL
  1668. /*
  1669. * Caller should check the value of presel to confirm if it needs to wait to show warning
  1670. */
  1671. static char *getreadline(char *prompt, char *path, char *curpath, int *presel)
  1672. {
  1673. /* Switch to current path for readline(3) */
  1674. if (chdir(path) == -1) {
  1675. printwarn(presel);
  1676. return NULL;
  1677. }
  1678. exitcurses();
  1679. char *input = readline(prompt);
  1680. refresh();
  1681. if (chdir(curpath) == -1) {
  1682. printwarn(presel);
  1683. free(input);
  1684. return NULL;
  1685. }
  1686. if (input && input[0]) {
  1687. add_history(input);
  1688. xstrlcpy(g_buf, input, CMD_LEN_MAX);
  1689. free(input);
  1690. return g_buf;
  1691. }
  1692. free(input);
  1693. return NULL;
  1694. }
  1695. #endif
  1696. /*
  1697. * Updates out with "dir/name or "/name"
  1698. * Returns the number of bytes copied including the terminating NULL byte
  1699. */
  1700. static size_t mkpath(char *dir, char *name, char *out)
  1701. {
  1702. size_t len;
  1703. /* Handle absolute path */
  1704. if (name[0] == '/')
  1705. return xstrlcpy(out, name, PATH_MAX);
  1706. /* Handle root case */
  1707. if (istopdir(dir))
  1708. len = 1;
  1709. else
  1710. len = xstrlcpy(out, dir, PATH_MAX);
  1711. out[len - 1] = '/'; // NOLINT
  1712. return (xstrlcpy(out + len, name, PATH_MAX - len) + len);
  1713. }
  1714. /*
  1715. * Create symbolic/hard link(s) to file(s) in selection list
  1716. * Returns the number of links created
  1717. */
  1718. static int xlink(char *suffix, char *path, char *buf, int *presel, int type)
  1719. {
  1720. int count = 0;
  1721. char *pbuf = pcopybuf, *fname;
  1722. size_t pos = 0, len, r;
  1723. int (*link_fn)(const char *, const char *) = NULL;
  1724. /* Check if selection is empty */
  1725. if (!copybufpos) {
  1726. printwait(messages[NONE_SELECTED], presel);
  1727. return -1;
  1728. }
  1729. if (type == 's') /* symbolic link */
  1730. link_fn = &symlink;
  1731. else /* hard link */
  1732. link_fn = &link;
  1733. while (pos < copybufpos) {
  1734. len = strlen(pbuf);
  1735. fname = xbasename(pbuf);
  1736. r = mkpath(path, fname, buf);
  1737. xstrlcpy(buf + r - 1, suffix, PATH_MAX - r - 1);
  1738. if (!link_fn(pbuf, buf))
  1739. ++count;
  1740. pos += len + 1;
  1741. pbuf += len + 1;
  1742. }
  1743. if (!count)
  1744. printwait("none created", presel);
  1745. return count;
  1746. }
  1747. static bool parsebmstr(void)
  1748. {
  1749. int i = 0;
  1750. char *bms = getenv(env_cfg[NNN_BMS]);
  1751. char *nextkey = bms;
  1752. if (!bms || !*bms)
  1753. return TRUE;
  1754. while (*bms && i < BM_MAX) {
  1755. if (bms == nextkey) {
  1756. bookmark[i].key = *bms;
  1757. if (*++bms != ':')
  1758. return FALSE;
  1759. if (*++bms == '\0')
  1760. return FALSE;
  1761. bookmark[i].loc = bms;
  1762. ++i;
  1763. }
  1764. if (*bms == ';') {
  1765. /* Remove trailing space */
  1766. if (i > 0 && *(bms - 1) == '/')
  1767. *(bms - 1) = '\0';
  1768. *bms = '\0';
  1769. nextkey = bms + 1;
  1770. }
  1771. ++bms;
  1772. }
  1773. if (i < BM_MAX) {
  1774. if (*bookmark[i - 1].loc == '\0')
  1775. return FALSE;
  1776. bookmark[i].key = '\0';
  1777. }
  1778. return TRUE;
  1779. }
  1780. /*
  1781. * Get the real path to a bookmark
  1782. *
  1783. * NULL is returned in case of no match, path resolution failure etc.
  1784. * buf would be modified, so check return value before access
  1785. */
  1786. static char *get_bm_loc(char *buf, int key)
  1787. {
  1788. int r = 0;
  1789. for (; bookmark[r].key && r < BM_MAX; ++r) {
  1790. if (bookmark[r].key == key) {
  1791. if (bookmark[r].loc[0] == '~') {
  1792. ssize_t len = strlen(home);
  1793. ssize_t loclen = strlen(bookmark[r].loc);
  1794. if (!buf)
  1795. buf = (char *)malloc(len + loclen);
  1796. xstrlcpy(buf, home, len + 1);
  1797. xstrlcpy(buf + len, bookmark[r].loc + 1, loclen);
  1798. return buf;
  1799. }
  1800. return realpath(bookmark[r].loc, buf);
  1801. }
  1802. }
  1803. DPRINTF_S("Invalid key");
  1804. return NULL;
  1805. }
  1806. static inline void resetdircolor(int flags)
  1807. {
  1808. if (cfg.dircolor && !(flags & DIR_OR_LINK_TO_DIR)) {
  1809. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  1810. cfg.dircolor = 0;
  1811. }
  1812. }
  1813. /*
  1814. * Replace escape characters in a string with '?'
  1815. * Adjust string length to maxcols if > 0;
  1816. * Max supported str length: NAME_MAX;
  1817. *
  1818. * Interestingly, note that unescape() uses g_buf. What happens if
  1819. * str also points to g_buf? In this case we assume that the caller
  1820. * acknowledges that it's OK to lose the data in g_buf after this
  1821. * call to unescape().
  1822. * The API, on its part, first converts str to multibyte (after which
  1823. * it doesn't touch str anymore). Only after that it starts modifying
  1824. * g_buf. This is a phased operation.
  1825. */
  1826. static char *unescape(const char *str, uint maxcols)
  1827. {
  1828. static wchar_t wbuf[NAME_MAX + 1] __attribute__ ((aligned));
  1829. wchar_t *buf = wbuf;
  1830. size_t lencount = 0;
  1831. /* Convert multi-byte to wide char */
  1832. size_t len = mbstowcs(wbuf, str, NAME_MAX);
  1833. while (*buf && lencount <= maxcols) {
  1834. if (*buf <= '\x1f' || *buf == '\x7f')
  1835. *buf = '\?';
  1836. ++buf;
  1837. ++lencount;
  1838. }
  1839. len = lencount = wcswidth(wbuf, len);
  1840. /* Reduce number of wide chars to max columns */
  1841. if (len > maxcols) {
  1842. lencount = maxcols + 1;
  1843. /* Reduce wide chars one by one till it fits */
  1844. while (len > maxcols)
  1845. len = wcswidth(wbuf, --lencount);
  1846. wbuf[lencount] = L'\0';
  1847. }
  1848. /* Convert wide char to multi-byte */
  1849. wcstombs(g_buf, wbuf, NAME_MAX);
  1850. return g_buf;
  1851. }
  1852. static char *coolsize(off_t size)
  1853. {
  1854. const char * const U = "BKMGTPEZY";
  1855. static char size_buf[12]; /* Buffer to hold human readable size */
  1856. off_t rem = 0;
  1857. size_t ret;
  1858. int i = 0;
  1859. while (size >= 1024) {
  1860. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  1861. size >>= 10;
  1862. ++i;
  1863. }
  1864. if (i == 1) {
  1865. rem = (rem * 1000) >> 10;
  1866. rem /= 10;
  1867. if (rem % 10 >= 5) {
  1868. rem = (rem / 10) + 1;
  1869. if (rem == 10) {
  1870. ++size;
  1871. rem = 0;
  1872. }
  1873. } else
  1874. rem /= 10;
  1875. } else if (i == 2) {
  1876. rem = (rem * 1000) >> 10;
  1877. if (rem % 10 >= 5) {
  1878. rem = (rem / 10) + 1;
  1879. if (rem == 100) {
  1880. ++size;
  1881. rem = 0;
  1882. }
  1883. } else
  1884. rem /= 10;
  1885. } else if (i > 0) {
  1886. rem = (rem * 10000) >> 10;
  1887. if (rem % 10 >= 5) {
  1888. rem = (rem / 10) + 1;
  1889. if (rem == 1000) {
  1890. ++size;
  1891. rem = 0;
  1892. }
  1893. } else
  1894. rem /= 10;
  1895. }
  1896. if (i > 0 && i < 6 && rem) {
  1897. ret = xstrlcpy(size_buf, xitoa(size), 12);
  1898. size_buf[ret - 1] = '.';
  1899. char *frac = xitoa(rem);
  1900. size_t toprint = i > 3 ? 3 : i;
  1901. size_t len = strlen(frac);
  1902. if (len < toprint) {
  1903. size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
  1904. xstrlcpy(size_buf + ret + (toprint - len), frac, len + 1);
  1905. } else
  1906. xstrlcpy(size_buf + ret, frac, toprint + 1);
  1907. ret += toprint;
  1908. } else {
  1909. ret = xstrlcpy(size_buf, size ? xitoa(size) : "0", 12);
  1910. --ret;
  1911. }
  1912. size_buf[ret] = U[i];
  1913. size_buf[ret + 1] = '\0';
  1914. return size_buf;
  1915. }
  1916. static void printent(const struct entry *ent, int sel, uint namecols)
  1917. {
  1918. const char *pname = unescape(ent->name, namecols);
  1919. const char cp = (ent->flags & FILE_COPIED) ? '+' : ' ';
  1920. char ind[2] = {'\0', '\0'};
  1921. mode_t mode = ent->mode;
  1922. switch (mode & S_IFMT) {
  1923. case S_IFREG:
  1924. if (mode & 0100)
  1925. ind[0] = '*';
  1926. break;
  1927. case S_IFDIR:
  1928. ind[0] = '/';
  1929. break;
  1930. case S_IFLNK:
  1931. ind[0] = '@';
  1932. break;
  1933. case S_IFSOCK:
  1934. ind[0] = '=';
  1935. break;
  1936. case S_IFIFO:
  1937. ind[0] = '|';
  1938. break;
  1939. case S_IFBLK: // fallthrough
  1940. case S_IFCHR:
  1941. break;
  1942. default:
  1943. ind[0] = '?';
  1944. break;
  1945. }
  1946. /* Directories are always shown on top */
  1947. resetdircolor(ent->flags);
  1948. if (sel)
  1949. attron(A_REVERSE);
  1950. printw("%c%s%s\n", cp, pname, ind);
  1951. if (sel)
  1952. attroff(A_REVERSE);
  1953. }
  1954. static void printent_long(const struct entry *ent, int sel, uint namecols)
  1955. {
  1956. char timebuf[18], permbuf[4], ind1 = '\0', ind2[] = "\0\0";
  1957. const char cp = (ent->flags & FILE_COPIED) ? '+' : ' ';
  1958. /* Timestamp */
  1959. strftime(timebuf, 18, "%F %R", localtime(&ent->t));
  1960. /* Permissions */
  1961. permbuf[0] = '0' + ((ent->mode >> 6) & 7);
  1962. permbuf[1] = '0' + ((ent->mode >> 3) & 7);
  1963. permbuf[2] = '0' + (ent->mode & 7);
  1964. permbuf[3] = '\0';
  1965. /* Trim escape chars from name */
  1966. const char *pname = unescape(ent->name, namecols);
  1967. /* Directories are always shown on top */
  1968. resetdircolor(ent->flags);
  1969. if (sel)
  1970. attron(A_REVERSE);
  1971. switch (ent->mode & S_IFMT) {
  1972. case S_IFREG:
  1973. if (ent->mode & 0100)
  1974. printw("%c%-16.16s %s %8.8s* %s*\n", cp, timebuf, permbuf,
  1975. coolsize(cfg.blkorder ? ent->blocks << BLK_SHIFT : ent->size), pname);
  1976. else
  1977. printw("%c%-16.16s %s %8.8s %s\n", cp, timebuf, permbuf,
  1978. coolsize(cfg.blkorder ? ent->blocks << BLK_SHIFT : ent->size), pname);
  1979. break;
  1980. case S_IFDIR:
  1981. if (cfg.blkorder)
  1982. printw("%c%-16.16s %s %8.8s/ %s/\n",
  1983. cp, timebuf, permbuf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1984. else
  1985. printw("%c%-16.16s %s / %s/\n", cp, timebuf, permbuf, pname);
  1986. break;
  1987. case S_IFLNK:
  1988. if (ent->flags & DIR_OR_LINK_TO_DIR)
  1989. printw("%c%-16.16s %s @/ %s@\n", cp, timebuf, permbuf, pname);
  1990. else
  1991. printw("%c%-16.16s %s @ %s@\n", cp, timebuf, permbuf, pname);
  1992. break;
  1993. case S_IFSOCK:
  1994. ind1 = ind2[0] = '='; // fallthrough
  1995. case S_IFIFO:
  1996. if (!ind1)
  1997. ind1 = ind2[0] = '|'; // fallthrough
  1998. case S_IFBLK:
  1999. if (!ind1)
  2000. ind1 = 'b'; // fallthrough
  2001. case S_IFCHR:
  2002. if (!ind1)
  2003. ind1 = 'c'; // fallthrough
  2004. default:
  2005. if (!ind1)
  2006. ind1 = ind2[0] = '?';
  2007. printw("%c%-16.16s %s %c %s%s\n", cp, timebuf, permbuf, ind1, pname, ind2);
  2008. break;
  2009. }
  2010. if (sel)
  2011. attroff(A_REVERSE);
  2012. }
  2013. static void (*printptr)(const struct entry *ent, int sel, uint namecols) = &printent;
  2014. static void savecurctx(settings *curcfg, char *path, char *curname, int r /* next context num */)
  2015. {
  2016. settings cfg = *curcfg;
  2017. bool copymode = cfg.copymode ? TRUE : FALSE;
  2018. #ifdef DIR_LIMITED_COPY
  2019. g_crc = 0;
  2020. #endif
  2021. /* Save current context */
  2022. xstrlcpy(g_ctx[cfg.curctx].c_name, curname, NAME_MAX + 1);
  2023. g_ctx[cfg.curctx].c_cfg = cfg;
  2024. if (g_ctx[r].c_cfg.ctxactive) { /* Switch to saved context */
  2025. /* Switch light/detail mode */
  2026. if (cfg.showdetail != g_ctx[r].c_cfg.showdetail)
  2027. /* set the reverse */
  2028. printptr = cfg.showdetail ? &printent : &printent_long;
  2029. cfg = g_ctx[r].c_cfg;
  2030. } else { /* Setup a new context from current context */
  2031. g_ctx[r].c_cfg.ctxactive = 1;
  2032. xstrlcpy(g_ctx[r].c_path, path, PATH_MAX);
  2033. g_ctx[r].c_last[0] = '\0';
  2034. xstrlcpy(g_ctx[r].c_name, curname, NAME_MAX + 1);
  2035. g_ctx[r].c_fltr[0] = g_ctx[r].c_fltr[1] = '\0';
  2036. g_ctx[r].c_cfg = cfg;
  2037. g_ctx[r].c_cfg.runplugin = 0;
  2038. }
  2039. /* Continue copy mode */
  2040. cfg.copymode = copymode;
  2041. cfg.curctx = r;
  2042. *curcfg = cfg;
  2043. }
  2044. /*
  2045. * Gets only a single line (that's what we need
  2046. * for now) or shows full command output in pager.
  2047. *
  2048. * If page is valid, returns NULL
  2049. */
  2050. static char *get_output(char *buf, const size_t bytes, const char *file,
  2051. const char *arg1, const char *arg2, const bool page)
  2052. {
  2053. pid_t pid;
  2054. int pipefd[2];
  2055. FILE *pf;
  2056. int tmp, flags;
  2057. char *ret = NULL;
  2058. if (pipe(pipefd) == -1)
  2059. errexit();
  2060. for (tmp = 0; tmp < 2; ++tmp) {
  2061. /* Get previous flags */
  2062. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  2063. /* Set bit for non-blocking flag */
  2064. flags |= O_NONBLOCK;
  2065. /* Change flags on fd */
  2066. fcntl(pipefd[tmp], F_SETFL, flags);
  2067. }
  2068. pid = fork();
  2069. if (pid == 0) {
  2070. /* In child */
  2071. close(pipefd[0]);
  2072. dup2(pipefd[1], STDOUT_FILENO);
  2073. dup2(pipefd[1], STDERR_FILENO);
  2074. close(pipefd[1]);
  2075. execlp(file, file, arg1, arg2, NULL);
  2076. _exit(1);
  2077. }
  2078. /* In parent */
  2079. waitpid(pid, &tmp, 0);
  2080. close(pipefd[1]);
  2081. if (!page) {
  2082. pf = fdopen(pipefd[0], "r");
  2083. if (pf) {
  2084. ret = fgets(buf, bytes, pf);
  2085. close(pipefd[0]);
  2086. }
  2087. return ret;
  2088. }
  2089. pid = fork();
  2090. if (pid == 0) {
  2091. /* Show in pager in child */
  2092. dup2(pipefd[0], STDIN_FILENO);
  2093. close(pipefd[0]);
  2094. spawn(pager, NULL, NULL, NULL, F_CLI);
  2095. _exit(1);
  2096. }
  2097. /* In parent */
  2098. waitpid(pid, &tmp, 0);
  2099. close(pipefd[0]);
  2100. return NULL;
  2101. }
  2102. static bool getutil(const char *util)
  2103. {
  2104. char buf[8];
  2105. if (!get_output(buf, 8, "which", util, NULL, FALSE))
  2106. return FALSE;
  2107. return TRUE;
  2108. }
  2109. /*
  2110. * Follows the stat(1) output closely
  2111. */
  2112. static bool show_stats(const char *fpath, const char *fname, const struct stat *sb)
  2113. {
  2114. int fd;
  2115. char *p, *begin = g_buf;
  2116. size_t r;
  2117. FILE *fp;
  2118. fd = create_tmp_file();
  2119. if (fd == -1)
  2120. return FALSE;
  2121. r = xstrlcpy(g_buf, "stat \"", PATH_MAX);
  2122. r += xstrlcpy(g_buf + r - 1, fpath, PATH_MAX);
  2123. g_buf[r - 2] = '\"';
  2124. g_buf[r - 1] = '\0';
  2125. DPRINTF_S(g_buf);
  2126. fp = popen(g_buf, "r");
  2127. if (fp) {
  2128. while (fgets(g_buf, CMD_LEN_MAX - 1, fp))
  2129. dprintf(fd, "%s", g_buf);
  2130. pclose(fp);
  2131. }
  2132. if (S_ISREG(sb->st_mode)) {
  2133. /* Show file(1) output */
  2134. p = get_output(g_buf, CMD_LEN_MAX, "file", "-b", fpath, FALSE);
  2135. if (p) {
  2136. dprintf(fd, "\n\n ");
  2137. while (*p) {
  2138. if (*p == ',') {
  2139. *p = '\0';
  2140. dprintf(fd, " %s\n", begin);
  2141. begin = p + 1;
  2142. }
  2143. ++p;
  2144. }
  2145. dprintf(fd, " %s", begin);
  2146. }
  2147. }
  2148. dprintf(fd, "\n\n");
  2149. close(fd);
  2150. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  2151. unlink(g_tmpfpath);
  2152. return TRUE;
  2153. }
  2154. static size_t get_fs_info(const char *path, bool type)
  2155. {
  2156. struct statvfs svb;
  2157. if (statvfs(path, &svb) == -1)
  2158. return 0;
  2159. if (type == CAPACITY)
  2160. return svb.f_blocks << ffs((int)(svb.f_bsize >> 1));
  2161. return svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
  2162. }
  2163. static bool show_mediainfo(const char *fpath, const char *arg)
  2164. {
  2165. if (!getutil(utils[cfg.metaviewer]))
  2166. return FALSE;
  2167. exitcurses();
  2168. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, TRUE);
  2169. refresh();
  2170. return TRUE;
  2171. }
  2172. /* List or extract archive */
  2173. static void handle_archive(char *fpath, const char *dir, char op)
  2174. {
  2175. char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
  2176. char *util;
  2177. if (getutil(utils[ATOOL])) {
  2178. util = utils[ATOOL];
  2179. arg[1] = op;
  2180. arg[2] = '\0';
  2181. } else if (getutil(utils[BSDTAR])) {
  2182. util = utils[BSDTAR];
  2183. if (op == 'x')
  2184. arg[1] = op;
  2185. } else if (is_suffix(fpath, ".zip")) {
  2186. util = utils[UNZIP];
  2187. arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
  2188. arg[2] = '\0';
  2189. } else {
  2190. util = utils[TAR];
  2191. if (op == 'x')
  2192. arg[1] = op;
  2193. }
  2194. if (op == 'x') { /* extract */
  2195. spawn(util, arg, fpath, dir, F_NORMAL);
  2196. } else { /* list */
  2197. exitcurses();
  2198. get_output(NULL, 0, util, arg, fpath, TRUE);
  2199. refresh();
  2200. }
  2201. }
  2202. static char *visit_parent(char *path, char *newpath, int *presel)
  2203. {
  2204. char *dir;
  2205. /* There is no going back */
  2206. if (istopdir(path)) {
  2207. /* Continue in navigate-as-you-type mode, if enabled */
  2208. if (cfg.filtermode)
  2209. *presel = FILTER;
  2210. return NULL;
  2211. }
  2212. /* Use a copy as dirname() may change the string passed */
  2213. xstrlcpy(newpath, path, PATH_MAX);
  2214. dir = dirname(newpath);
  2215. if (access(dir, R_OK) == -1) {
  2216. printwarn(presel);
  2217. return NULL;
  2218. }
  2219. return dir;
  2220. }
  2221. static bool execute_file(int cur, char *path, char *newpath, int *presel)
  2222. {
  2223. if (!ndents)
  2224. return FALSE;
  2225. /* Check if this is a directory */
  2226. if (!S_ISREG(dents[cur].mode)) {
  2227. printwait("not regular file", presel);
  2228. return FALSE;
  2229. }
  2230. /* Check if file is executable */
  2231. if (!(dents[cur].mode & 0100)) {
  2232. printwait("permission denied", presel);
  2233. return FALSE;
  2234. }
  2235. mkpath(path, dents[cur].name, newpath);
  2236. spawn(newpath, NULL, NULL, path, F_NORMAL);
  2237. return TRUE;
  2238. }
  2239. static bool create_dir(const char *path)
  2240. {
  2241. if (!xdiraccess(path)) {
  2242. if (errno != ENOENT)
  2243. return FALSE;
  2244. if (mkdir(path, 0755) == -1)
  2245. return FALSE;
  2246. }
  2247. return TRUE;
  2248. }
  2249. static bool sshfs_mount(char *path, char *newpath, int *presel)
  2250. {
  2251. uchar flag = F_NORMAL;
  2252. int r;
  2253. char *tmp, *env, *cmd = "sshfs";
  2254. if (!getutil(cmd)) {
  2255. printwait(messages[UTIL_MISSING], presel);
  2256. return FALSE;
  2257. }
  2258. tmp = xreadline(NULL, "host: ");
  2259. if (!tmp[0])
  2260. return FALSE;
  2261. /* Create the mount point */
  2262. mkpath(cfgdir, tmp, newpath);
  2263. if (!create_dir(newpath)) {
  2264. printwait(strerror(errno), presel);
  2265. return FALSE;
  2266. }
  2267. /* Convert "Host" to "Host:" */
  2268. r = strlen(tmp);
  2269. tmp[r] = ':';
  2270. tmp[r + 1] = '\0';
  2271. env = getenv("NNN_SSHFS_OPTS");
  2272. if (env)
  2273. flag |= F_MULTI;
  2274. else
  2275. env = cmd;
  2276. /* Connect to remote */
  2277. if (spawn(env, tmp, newpath, NULL, flag)) {
  2278. printwait("mount failed", presel);
  2279. return FALSE;
  2280. }
  2281. return TRUE;
  2282. }
  2283. static bool sshfs_unmount(char *path, char *newpath, int *presel)
  2284. {
  2285. static char cmd[] = "fusermount3"; /* Arch Linux utility */
  2286. static bool found = FALSE;
  2287. char *tmp;
  2288. /* On Ubuntu it's fusermount */
  2289. if (!found && !getutil(cmd)) {
  2290. cmd[10] = '\0';
  2291. found = TRUE;
  2292. }
  2293. tmp = xreadline(NULL, "host: ");
  2294. if (!tmp[0])
  2295. return FALSE;
  2296. /* Create the mount point */
  2297. mkpath(cfgdir, tmp, newpath);
  2298. if (!xdiraccess(newpath)) {
  2299. *presel = MSGWAIT;
  2300. return FALSE;
  2301. }
  2302. if (spawn(cmd, "-u", newpath, NULL, F_NORMAL)) {
  2303. printwait("unmount failed", presel);
  2304. return FALSE;
  2305. }
  2306. return TRUE;
  2307. }
  2308. static void lock_terminal(void)
  2309. {
  2310. char *tmp = utils[LOCKER];
  2311. if (!getutil(tmp))
  2312. tmp = utils[CMATRIX];;
  2313. spawn(tmp, NULL, NULL, NULL, F_NORMAL);
  2314. }
  2315. /*
  2316. * The help string tokens (each line) start with a HEX value
  2317. * which indicates the number of spaces to print before the
  2318. * particular token. This method was chosen instead of a flat
  2319. * string because the number of bytes in help was increasing
  2320. * the binary size by around a hundred bytes. This would only
  2321. * have increased as we keep adding new options.
  2322. */
  2323. static bool show_help(const char *path)
  2324. {
  2325. int i = 0, fd;
  2326. const char *start, *end;
  2327. const char helpstr[] = {
  2328. "0\n"
  2329. "1NAVIGATION\n"
  2330. "a↑ k Up PgUp ^U Scroll up\n"
  2331. "a↓ j Down PgDn ^D Scroll down\n"
  2332. "a← h Parent dir ~ ` @ - HOME, /, start, last\n"
  2333. "8↵ → l Open file/dir . Toggle show hidden\n"
  2334. "4Home g ^A First entry G ^E Last entry\n"
  2335. "cb Pin current dir ^B Go to pinned dir\n"
  2336. "7Tab ^I Next context d Toggle detail view\n"
  2337. "9, ^/ Leader key N LeadN Context N\n"
  2338. "c/ Filter/Lead Ins ^T Toggle nav-as-you-type\n"
  2339. "aEsc Exit prompt ^L Redraw/clear prompt\n"
  2340. "b^G Quit and cd q Quit context\n"
  2341. "9Q ^Q Quit ? Help, config\n"
  2342. "1FILES\n"
  2343. "b^O Open with... n Create new/link\n"
  2344. "cD File details ^R Rename/duplicate\n"
  2345. "5⎵ ^K / Y Select entry/all r Batch rename\n"
  2346. "9K ^Y Toggle selection y List selection\n"
  2347. "cP Copy selection X Delete selection\n"
  2348. "cV Move selection ^X Delete entry\n"
  2349. "cf Create archive m M Brief/full mediainfo\n"
  2350. "b^F Extract archive F List archive\n"
  2351. "ce Edit in EDITOR p Open in PAGER\n"
  2352. "1ORDER TOGGLES\n"
  2353. "b^J du E Extn S Apparent du\n"
  2354. "b^W Random s Size t Time modified\n"
  2355. "1MISC\n"
  2356. "9! ^] Spawn SHELL C Execute entry\n"
  2357. "9R ^V Pick plugin L Lock terminal\n"
  2358. "cc SSHFS mount u Unmount\n"
  2359. "b^P Prompt ^N Note = Launcher\n"};
  2360. fd = create_tmp_file();
  2361. if (fd == -1)
  2362. return FALSE;
  2363. start = end = helpstr;
  2364. while (*end) {
  2365. if (*end == '\n') {
  2366. dprintf(fd, "%*c%.*s",
  2367. xchartohex(*start), ' ', (int)(end - start), start + 1);
  2368. start = end + 1;
  2369. }
  2370. ++end;
  2371. }
  2372. dprintf(fd, "\nVOLUME: %s of ", coolsize(get_fs_info(path, FREE)));
  2373. dprintf(fd, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  2374. if (bookmark[0].loc) {
  2375. dprintf(fd, "BOOKMARKS\n");
  2376. for (; i < BM_MAX; ++i)
  2377. if (bookmark[i].key)
  2378. dprintf(fd, " %c: %s\n", (char)bookmark[i].key, bookmark[i].loc);
  2379. else
  2380. break;
  2381. dprintf(fd, "\n");
  2382. }
  2383. for (i = NNN_OPENER; i <= NNN_TRASH; ++i) {
  2384. start = getenv(env_cfg[i]);
  2385. if (start)
  2386. dprintf(fd, "%s: %s\n", env_cfg[i], start);
  2387. }
  2388. if (g_cppath)
  2389. dprintf(fd, "SELECTION FILE: %s\n", g_cppath);
  2390. dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
  2391. close(fd);
  2392. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  2393. unlink(g_tmpfpath);
  2394. return TRUE;
  2395. }
  2396. static int sum_bsizes(const char *fpath, const struct stat *sb,
  2397. int typeflag, struct FTW *ftwbuf)
  2398. {
  2399. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  2400. ent_blocks += sb->st_blocks;
  2401. ++num_files;
  2402. return 0;
  2403. }
  2404. static int sum_sizes(const char *fpath, const struct stat *sb,
  2405. int typeflag, struct FTW *ftwbuf)
  2406. {
  2407. if (sb->st_size && (typeflag == FTW_F || typeflag == FTW_D))
  2408. ent_blocks += sb->st_size;
  2409. ++num_files;
  2410. return 0;
  2411. }
  2412. static void dentfree(void)
  2413. {
  2414. free(pnamebuf);
  2415. free(dents);
  2416. }
  2417. static int dentfill(char *path, struct entry **dents)
  2418. {
  2419. static uint open_max;
  2420. int n = 0, count, flags = 0;
  2421. ulong num_saved;
  2422. struct dirent *dp;
  2423. char *namep, *pnb, *buf = NULL;
  2424. struct entry *dentp;
  2425. size_t off = 0, namebuflen = NAMEBUF_INCR;
  2426. struct stat sb_path, sb;
  2427. DIR *dirp = opendir(path);
  2428. if (!dirp)
  2429. return 0;
  2430. int fd = dirfd(dirp);
  2431. if (cfg.blkorder) {
  2432. num_files = 0;
  2433. dir_blocks = 0;
  2434. buf = (char *)alloca(strlen(path) + NAME_MAX + 2);
  2435. if (fstatat(fd, path, &sb_path, 0) == -1) {
  2436. closedir(dirp);
  2437. printwarn(NULL);
  2438. return 0;
  2439. }
  2440. /* Increase current open file descriptor limit */
  2441. if (!open_max)
  2442. open_max = max_openfds();
  2443. }
  2444. dp = readdir(dirp);
  2445. if (!dp)
  2446. goto exit;
  2447. if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
  2448. /*
  2449. * Optimization added for filesystems which support dirent.d_type
  2450. * see readdir(3)
  2451. * Known drawbacks:
  2452. * - the symlink size is set to 0
  2453. * - the modification time of the symlink is set to that of the target file
  2454. */
  2455. flags = AT_SYMLINK_NOFOLLOW;
  2456. }
  2457. do {
  2458. namep = dp->d_name;
  2459. /* Skip self and parent */
  2460. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  2461. continue;
  2462. if (!cfg.showhidden && namep[0] == '.') {
  2463. if (!cfg.blkorder)
  2464. continue;
  2465. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  2466. continue;
  2467. if (S_ISDIR(sb.st_mode)) {
  2468. if (sb_path.st_dev == sb.st_dev) {
  2469. ent_blocks = 0;
  2470. mkpath(path, namep, buf);
  2471. mvprintw(xlines - 1, 0, "scanning %s [^C aborts]\n",
  2472. xbasename(buf));
  2473. refresh();
  2474. if (nftw(buf, nftw_fn, open_max,
  2475. FTW_MOUNT | FTW_PHYS) == -1) {
  2476. DPRINTF_S("nftw failed");
  2477. dir_blocks += (cfg.apparentsz
  2478. ? sb.st_size
  2479. : sb.st_blocks);
  2480. } else
  2481. dir_blocks += ent_blocks;
  2482. if (interrupted) {
  2483. closedir(dirp);
  2484. return n;
  2485. }
  2486. }
  2487. } else {
  2488. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  2489. ++num_files;
  2490. }
  2491. continue;
  2492. }
  2493. if (fstatat(fd, namep, &sb, flags) == -1) {
  2494. DPRINTF_S(namep);
  2495. continue;
  2496. }
  2497. if (n == total_dents) {
  2498. total_dents += ENTRY_INCR;
  2499. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  2500. if (!*dents) {
  2501. free(pnamebuf);
  2502. closedir(dirp);
  2503. errexit();
  2504. }
  2505. DPRINTF_P(*dents);
  2506. }
  2507. /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  2508. if (namebuflen - off < NAME_MAX + 1) {
  2509. namebuflen += NAMEBUF_INCR;
  2510. pnb = pnamebuf;
  2511. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  2512. if (!pnamebuf) {
  2513. free(*dents);
  2514. closedir(dirp);
  2515. errexit();
  2516. }
  2517. DPRINTF_P(pnamebuf);
  2518. /* realloc() may result in memory move, we must re-adjust if that happens */
  2519. if (pnb != pnamebuf) {
  2520. dentp = *dents;
  2521. dentp->name = pnamebuf;
  2522. for (count = 1; count < n; ++dentp, ++count)
  2523. /* Current filename starts at last filename start + length */
  2524. (dentp + 1)->name = (char *)((size_t)dentp->name
  2525. + dentp->nlen);
  2526. }
  2527. }
  2528. dentp = *dents + n;
  2529. /* Selection file name */
  2530. dentp->name = (char *)((size_t)pnamebuf + off);
  2531. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  2532. off += dentp->nlen;
  2533. /* Copy other fields */
  2534. dentp->t = sb.st_mtime;
  2535. if (dp->d_type == DT_LNK && !flags) { /* Do not add sizes for links */
  2536. dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
  2537. dentp->size = 0;
  2538. } else {
  2539. dentp->mode = sb.st_mode;
  2540. dentp->size = sb.st_size;
  2541. }
  2542. dentp->flags = 0;
  2543. if (cfg.blkorder) {
  2544. if (S_ISDIR(sb.st_mode)) {
  2545. ent_blocks = 0;
  2546. num_saved = num_files + 1;
  2547. mkpath(path, namep, buf);
  2548. mvprintw(xlines - 1, 0, "scanning %s [^C aborts]\n", xbasename(buf));
  2549. refresh();
  2550. if (nftw(buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  2551. DPRINTF_S("nftw failed");
  2552. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  2553. } else
  2554. dentp->blocks = ent_blocks;
  2555. if (sb_path.st_dev == sb.st_dev) // NOLINT
  2556. dir_blocks += dentp->blocks;
  2557. else
  2558. num_files = num_saved;
  2559. if (interrupted) {
  2560. closedir(dirp);
  2561. return n;
  2562. }
  2563. } else {
  2564. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  2565. dir_blocks += dentp->blocks;
  2566. ++num_files;
  2567. }
  2568. }
  2569. if (flags) {
  2570. /* Flag if this is a dir or symlink to a dir */
  2571. if (S_ISLNK(sb.st_mode)) {
  2572. sb.st_mode = 0;
  2573. fstatat(fd, namep, &sb, 0);
  2574. }
  2575. if (S_ISDIR(sb.st_mode))
  2576. dentp->flags |= DIR_OR_LINK_TO_DIR;
  2577. } else if (dp->d_type == DT_DIR || (dp->d_type == DT_LNK && S_ISDIR(sb.st_mode)))
  2578. dentp->flags |= DIR_OR_LINK_TO_DIR;
  2579. ++n;
  2580. } while ((dp = readdir(dirp)));
  2581. exit:
  2582. /* Should never be null */
  2583. if (closedir(dirp) == -1) {
  2584. dentfree();
  2585. errexit();
  2586. }
  2587. return n;
  2588. }
  2589. /*
  2590. * Return the position of the matching entry or 0 otherwise
  2591. * Note there's no NULL check for fname
  2592. */
  2593. static int dentfind(const char *fname, int n)
  2594. {
  2595. int i = 0;
  2596. for (; i < n; ++i)
  2597. if (xstrcmp(fname, dents[i].name) == 0)
  2598. return i;
  2599. return 0;
  2600. }
  2601. static void populate(char *path, char *lastname)
  2602. {
  2603. #ifdef DBGMODE
  2604. struct timespec ts1, ts2;
  2605. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  2606. #endif
  2607. ndents = dentfill(path, &dents);
  2608. if (!ndents)
  2609. return;
  2610. if (!cfg.wild)
  2611. qsort(dents, ndents, sizeof(*dents), entrycmp);
  2612. #ifdef DBGMODE
  2613. clock_gettime(CLOCK_REALTIME, &ts2);
  2614. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  2615. #endif
  2616. /* Find cur from history */
  2617. /* No NULL check for lastname, always points to an array */
  2618. if (!*lastname)
  2619. move_cursor(0, 0);
  2620. else
  2621. move_cursor(dentfind(lastname, ndents), 0);
  2622. }
  2623. static void move_cursor(int target, int ignore_scrolloff)
  2624. {
  2625. int delta, scrolloff, onscreen = xlines - 4;
  2626. target = MAX(0, MIN(ndents - 1, target));
  2627. delta = target - cur;
  2628. cur = target;
  2629. if (!ignore_scrolloff) {
  2630. scrolloff = MIN(SCROLLOFF, onscreen >> 1);
  2631. /*
  2632. * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
  2633. * margin area, but when ignore_scrolloff is 0, act like a boa
  2634. * constrictor and squeeze the cursor towards the middle region of the
  2635. * screen by allowing it to move inward and disallowing it to move
  2636. * outward (deeper into the scrolloff margin area).
  2637. */
  2638. if (cur < curscroll + scrolloff && delta < 0)
  2639. curscroll += delta;
  2640. else if (cur > curscroll + onscreen - scrolloff - 1 && delta > 0)
  2641. curscroll += delta;
  2642. }
  2643. curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
  2644. curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
  2645. }
  2646. static void redraw(char *path)
  2647. {
  2648. xlines = LINES;
  2649. xcols = COLS;
  2650. int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
  2651. int lastln = xlines, onscreen = xlines - 4;
  2652. int i, attrs;
  2653. char buf[12];
  2654. char c;
  2655. --lastln;
  2656. /* Clear screen */
  2657. erase();
  2658. /* Enforce scroll/cursor invariants */
  2659. move_cursor(cur, 1);
  2660. #ifdef DIR_LIMITED_COPY
  2661. if (cfg.copymode)
  2662. if (g_crc != crc8fast((uchar *)dents, ndents * sizeof(struct entry))) {
  2663. cfg.copymode = 0;
  2664. DPRINTF_S("selection off");
  2665. }
  2666. #endif
  2667. /* Fail redraw if < than 11 columns, context info prints 10 chars */
  2668. if (ncols < 11) {
  2669. printmsg("too few columns!");
  2670. return;
  2671. }
  2672. DPRINTF_D(cur);
  2673. DPRINTF_S(path);
  2674. printw("[");
  2675. for (i = 0; i < CTX_MAX; ++i) {
  2676. if (!g_ctx[i].c_cfg.ctxactive)
  2677. printw("%d ", i + 1);
  2678. else if (cfg.curctx != i) {
  2679. attrs = COLOR_PAIR(i + 1) | A_BOLD | A_UNDERLINE;
  2680. attron(attrs);
  2681. printw("%d", i + 1);
  2682. attroff(attrs);
  2683. printw(" ");
  2684. } else {
  2685. /* Print current context in reverse */
  2686. attrs = COLOR_PAIR(i + 1) | A_BOLD | A_REVERSE;
  2687. attron(attrs);
  2688. printw("%d", i + 1);
  2689. attroff(attrs);
  2690. printw(" ");
  2691. }
  2692. }
  2693. printw("\b] "); /* 10 chars printed in total for contexts - "[1 2 3 4] " */
  2694. attron(A_UNDERLINE);
  2695. /* No text wrapping in cwd line, store the truncating char in c */
  2696. c = path[ncols - 11];
  2697. path[ncols - 11] = '\0';
  2698. printw("%s\n\n", path);
  2699. attroff(A_UNDERLINE);
  2700. path[ncols - 11] = c; /* Restore c */
  2701. /* Calculate the number of cols available to print entry name */
  2702. if (cfg.showdetail) {
  2703. /* Fallback to light mode if less than 35 columns */
  2704. if (ncols < 36) {
  2705. cfg.showdetail ^= 1;
  2706. printptr = &printent;
  2707. ncols -= 5;
  2708. } else
  2709. ncols -= 35;
  2710. } else
  2711. ncols -= 5;
  2712. if (!cfg.wild) {
  2713. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  2714. cfg.dircolor = 1;
  2715. }
  2716. /* Print listing */
  2717. for (i = curscroll; i < ndents && i < curscroll + onscreen; ++i) {
  2718. printptr(&dents[i], i == cur, ncols);
  2719. }
  2720. /* Must reset e.g. no files in dir */
  2721. if (cfg.dircolor) {
  2722. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  2723. cfg.dircolor = 0;
  2724. }
  2725. if (ndents) {
  2726. char sort[] = "\0 ";
  2727. if (cfg.mtimeorder)
  2728. sort[0] = 'T';
  2729. else if (cfg.sizeorder)
  2730. sort[0] = 'S';
  2731. else if (cfg.extnorder)
  2732. sort[0] = 'E';
  2733. /* We need to show filename as it may be truncated in directory listing */
  2734. if (!cfg.showdetail || !cfg.blkorder)
  2735. mvprintw(lastln, 0, "%d/%d %s[%s]\n", cur + 1, ndents, sort,
  2736. unescape(dents[cur].name, NAME_MAX));
  2737. else {
  2738. xstrlcpy(buf, coolsize(dir_blocks << BLK_SHIFT), 12);
  2739. c = cfg.apparentsz ? 'a' : 'd';
  2740. mvprintw(lastln, 0, "%d/%d %cu: %s (%lu files) free: %s [%s]\n",
  2741. cur + 1, ndents, c, buf, num_files,
  2742. coolsize(get_fs_info(path, FREE)),
  2743. unescape(dents[cur].name, NAME_MAX));
  2744. }
  2745. } else
  2746. printmsg("0/0");
  2747. }
  2748. static void browse(char *ipath)
  2749. {
  2750. char newpath[PATH_MAX] __attribute__ ((aligned));
  2751. char mark[PATH_MAX] __attribute__ ((aligned));
  2752. char rundir[PATH_MAX] __attribute__ ((aligned));
  2753. char runfile[NAME_MAX + 1] __attribute__ ((aligned));
  2754. int r = -1, fd, presel, ncp = 0, copystartid = 0, copyendid = 0, onscreen;
  2755. enum action sel;
  2756. bool dir_changed = FALSE;
  2757. struct stat sb;
  2758. char *path, *lastdir, *lastname, *dir, *tmp;
  2759. MEVENT event;
  2760. atexit(dentfree);
  2761. /* setup first context */
  2762. xstrlcpy(g_ctx[0].c_path, ipath, PATH_MAX); /* current directory */
  2763. path = g_ctx[0].c_path;
  2764. g_ctx[0].c_last[0] = g_ctx[0].c_name[0] = newpath[0] = mark[0] = '\0';
  2765. rundir[0] = runfile[0] = '\0';
  2766. lastdir = g_ctx[0].c_last; /* last visited directory */
  2767. lastname = g_ctx[0].c_name; /* last visited filename */
  2768. g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
  2769. g_ctx[0].c_cfg = cfg; /* current configuration */
  2770. cfg.filtermode ? (presel = FILTER) : (presel = 0);
  2771. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  2772. if (!dents)
  2773. errexit();
  2774. /* Allocate buffer to hold names */
  2775. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  2776. if (!pnamebuf)
  2777. errexit();
  2778. begin:
  2779. #ifdef LINUX_INOTIFY
  2780. if ((presel == FILTER || dir_changed) && inotify_wd >= 0) {
  2781. inotify_rm_watch(inotify_fd, inotify_wd);
  2782. inotify_wd = -1;
  2783. dir_changed = FALSE;
  2784. }
  2785. #elif defined(BSD_KQUEUE)
  2786. if ((presel == FILTER || dir_changed) && event_fd >= 0) {
  2787. close(event_fd);
  2788. event_fd = -1;
  2789. dir_changed = FALSE;
  2790. }
  2791. #endif
  2792. /* Can fail when permissions change while browsing.
  2793. * It's assumed that path IS a directory when we are here.
  2794. */
  2795. if (access(path, R_OK) == -1)
  2796. printwarn(&presel);
  2797. populate(path, lastname);
  2798. if (interrupted) {
  2799. interrupted = FALSE;
  2800. cfg.apparentsz = 0;
  2801. cfg.blkorder = 0;
  2802. BLK_SHIFT = 9;
  2803. presel = CONTROL('L');
  2804. }
  2805. #ifdef LINUX_INOTIFY
  2806. if (presel != FILTER && inotify_wd == -1)
  2807. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  2808. #elif defined(BSD_KQUEUE)
  2809. if (presel != FILTER && event_fd == -1) {
  2810. #if defined(O_EVTONLY)
  2811. event_fd = open(path, O_EVTONLY);
  2812. #else
  2813. event_fd = open(path, O_RDONLY);
  2814. #endif
  2815. if (event_fd >= 0)
  2816. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
  2817. EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  2818. }
  2819. #endif
  2820. while (1) {
  2821. redraw(path);
  2822. nochange:
  2823. /* Exit if parent has exited */
  2824. if (getppid() == 1)
  2825. _exit(0);
  2826. /* If CWD is deleted or moved or perms changed, find an accessible parent */
  2827. if (access(path, F_OK)) {
  2828. DPRINTF_S("directory inaccessible");
  2829. /* Save history */
  2830. xstrlcpy(lastname, xbasename(path), NAME_MAX + 1);
  2831. xstrlcpy(newpath, path, PATH_MAX);
  2832. while (true) {
  2833. dir = visit_parent(path, newpath, &presel);
  2834. if (istopdir(path) || istopdir(newpath)) {
  2835. if (!dir)
  2836. dir = dirname(newpath);
  2837. break;
  2838. }
  2839. if (!dir) {
  2840. xstrlcpy(path, newpath, PATH_MAX);
  2841. continue;
  2842. }
  2843. break;
  2844. }
  2845. xstrlcpy(path, dir, PATH_MAX);
  2846. setdirwatch();
  2847. mvprintw(xlines - 1, 0, "cannot access directory\n");
  2848. xdelay();
  2849. goto begin;
  2850. }
  2851. sel = nextsel(presel);
  2852. if (presel)
  2853. presel = 0;
  2854. switch (sel) {
  2855. case SEL_CLICK:
  2856. if (getmouse(&event) != OK)
  2857. goto nochange; // fallthrough
  2858. case SEL_BACK:
  2859. /* Handle clicking on a context at the top */
  2860. if (sel == SEL_CLICK && event.bstate == BUTTON1_CLICKED && event.y == 0) {
  2861. /* Get context from: "[1 2 3 4]..." */
  2862. r = event.x >> 1;
  2863. /* If clicked after contexts, go to parent */
  2864. if (r >= CTX_MAX)
  2865. sel = SEL_BACK;
  2866. else if (0 <= r && r < CTX_MAX && r != cfg.curctx) {
  2867. savecurctx(&cfg, path, dents[cur].name, r);
  2868. /* Reset the pointers */
  2869. path = g_ctx[r].c_path;
  2870. lastdir = g_ctx[r].c_last;
  2871. lastname = g_ctx[r].c_name;
  2872. setdirwatch();
  2873. goto begin;
  2874. }
  2875. }
  2876. if (sel == SEL_BACK) {
  2877. dir = visit_parent(path, newpath, &presel);
  2878. if (!dir)
  2879. goto nochange;
  2880. /* Save last working directory */
  2881. xstrlcpy(lastdir, path, PATH_MAX);
  2882. /* Save history */
  2883. xstrlcpy(lastname, xbasename(path), NAME_MAX + 1);
  2884. xstrlcpy(path, dir, PATH_MAX);
  2885. setdirwatch();
  2886. goto begin;
  2887. }
  2888. #if NCURSES_MOUSE_VERSION > 1
  2889. /* Scroll up */
  2890. if (event.bstate == BUTTON4_PRESSED && ndents) {
  2891. move_cursor((cur + ndents - 1) % ndents, 0);
  2892. break;
  2893. }
  2894. /* Scroll down */
  2895. if (event.bstate == BUTTON5_PRESSED && ndents) {
  2896. move_cursor((cur + 1) % ndents, 0);
  2897. break;
  2898. }
  2899. #endif
  2900. /* Toggle filter mode on left click on last 2 lines */
  2901. if (event.y >= xlines - 2) {
  2902. cfg.filtermode ^= 1;
  2903. if (cfg.filtermode) {
  2904. presel = FILTER;
  2905. goto nochange;
  2906. }
  2907. /* Start watching the directory */
  2908. dir_changed = TRUE;
  2909. if (ndents)
  2910. copycurname();
  2911. goto begin;
  2912. }
  2913. /* Handle clicking on a file */
  2914. r = curscroll + (event.y - 2);
  2915. if (2 <= event.y && event.y < xlines - 2 && r < ndents) {
  2916. move_cursor(r, 1);
  2917. /*Single click just selects, double click also opens */
  2918. if (event.bstate != BUTTON1_DOUBLE_CLICKED)
  2919. goto nochange;
  2920. } else {
  2921. if (cfg.filtermode)
  2922. presel = FILTER;
  2923. goto nochange; // fallthrough
  2924. }
  2925. case SEL_NAV_IN: // fallthrough
  2926. case SEL_GOIN:
  2927. /* Cannot descend in empty directories */
  2928. if (!ndents)
  2929. goto begin;
  2930. mkpath(path, dents[cur].name, newpath);
  2931. DPRINTF_S(newpath);
  2932. /* Cannot use stale data in entry, file may be missing by now */
  2933. if (stat(newpath, &sb) == -1) {
  2934. printwarn(&presel);
  2935. goto nochange;
  2936. }
  2937. DPRINTF_U(sb.st_mode);
  2938. switch (sb.st_mode & S_IFMT) {
  2939. case S_IFDIR:
  2940. if (access(newpath, R_OK) == -1) {
  2941. printwarn(&presel);
  2942. goto nochange;
  2943. }
  2944. /* Save last working directory */
  2945. xstrlcpy(lastdir, path, PATH_MAX);
  2946. xstrlcpy(path, newpath, PATH_MAX);
  2947. lastname[0] = '\0';
  2948. setdirwatch();
  2949. goto begin;
  2950. case S_IFREG:
  2951. {
  2952. /* If opened as vim plugin and Enter/^M pressed, pick */
  2953. if (cfg.picker && sel == SEL_GOIN) {
  2954. r = mkpath(path, dents[cur].name, newpath);
  2955. appendfpath(newpath, r);
  2956. writecp(pcopybuf, copybufpos - 1);
  2957. return;
  2958. }
  2959. /* If open file is disabled on right arrow or `l`, return */
  2960. if (cfg.nonavopen && sel == SEL_NAV_IN)
  2961. continue;
  2962. /* Handle plugin selection mode */
  2963. if (cfg.runplugin) {
  2964. if (!plugindir || (cfg.runctx != cfg.curctx)
  2965. /* Must be in plugin directory to select plugin */
  2966. || (strcmp(path, plugindir) != 0))
  2967. continue;
  2968. mkpath(path, dents[cur].name, newpath);
  2969. /* Copy to path so we can return back to earlier dir */
  2970. xstrlcpy(path, rundir, PATH_MAX);
  2971. if (runfile[0]) {
  2972. xstrlcpy(lastname, runfile, NAME_MAX);
  2973. spawn(newpath, lastname, NULL, path, F_NORMAL);
  2974. runfile[0] = '\0';
  2975. } else
  2976. spawn(newpath, NULL, NULL, path, F_NORMAL);
  2977. rundir[0] = '\0';
  2978. cfg.runplugin = 0;
  2979. setdirwatch();
  2980. goto begin;
  2981. }
  2982. /* If NNN_USE_EDITOR is set, open text in EDITOR */
  2983. if (cfg.useeditor &&
  2984. get_output(g_buf, CMD_LEN_MAX, "file", FILE_OPTS, newpath, FALSE)
  2985. && g_buf[0] == 't' && g_buf[1] == 'e' && g_buf[2] == 'x'
  2986. && g_buf[3] == g_buf[0] && g_buf[4] == '/') {
  2987. spawn(editor, newpath, NULL, path, F_CLI);
  2988. continue;
  2989. }
  2990. if (!sb.st_size) {
  2991. printwait("empty: use edit or open with", &presel);
  2992. goto nochange;
  2993. }
  2994. /* Invoke desktop opener as last resort */
  2995. spawn(opener, newpath, NULL, NULL, F_NOTRACE | F_NOWAIT);
  2996. continue;
  2997. }
  2998. default:
  2999. printwait("unsupported file", &presel);
  3000. goto nochange;
  3001. }
  3002. case SEL_NEXT:
  3003. if (ndents)
  3004. move_cursor((cur + 1) % ndents, 0);
  3005. break;
  3006. case SEL_PREV:
  3007. if (ndents)
  3008. move_cursor((cur + ndents - 1) % ndents, 0);
  3009. break;
  3010. case SEL_PGDN: // fallthrough
  3011. onscreen = xlines - 4;
  3012. move_cursor(curscroll + (onscreen - 1), 1);
  3013. curscroll += onscreen - 1;
  3014. break;
  3015. case SEL_CTRL_D:
  3016. onscreen = xlines - 4;
  3017. move_cursor(curscroll + (onscreen - 1), 1);
  3018. curscroll += onscreen >> 1;
  3019. break;
  3020. case SEL_PGUP: // fallthrough
  3021. onscreen = xlines - 4;
  3022. move_cursor(curscroll, 1);
  3023. curscroll -= onscreen - 1;
  3024. break;
  3025. case SEL_CTRL_U:
  3026. onscreen = xlines - 4;
  3027. move_cursor(curscroll, 1);
  3028. curscroll -= onscreen >> 1;
  3029. break;
  3030. case SEL_HOME:
  3031. move_cursor(0, 1);
  3032. break;
  3033. case SEL_END:
  3034. move_cursor(ndents - 1, 1);
  3035. break;
  3036. case SEL_CDHOME: // fallthrough
  3037. case SEL_CDBEGIN: // fallthrough
  3038. case SEL_CDLAST: // fallthrough
  3039. case SEL_CDROOT: // fallthrough
  3040. case SEL_VISIT:
  3041. switch (sel) {
  3042. case SEL_CDHOME:
  3043. dir = home;
  3044. break;
  3045. case SEL_CDBEGIN:
  3046. dir = ipath;
  3047. break;
  3048. case SEL_CDLAST:
  3049. dir = lastdir;
  3050. break;
  3051. case SEL_CDROOT:
  3052. dir = "/";
  3053. break;
  3054. default: /* case SEL_VISIT */
  3055. dir = mark;
  3056. break;
  3057. }
  3058. if (dir[0] == '\0') {
  3059. printwait("not set", &presel);
  3060. goto nochange;
  3061. }
  3062. if (!xdiraccess(dir)) {
  3063. presel = MSGWAIT;
  3064. goto nochange;
  3065. }
  3066. if (strcmp(path, dir) == 0)
  3067. goto nochange;
  3068. /* SEL_CDLAST: dir pointing to lastdir */
  3069. xstrlcpy(newpath, dir, PATH_MAX);
  3070. /* Save last working directory */
  3071. xstrlcpy(lastdir, path, PATH_MAX);
  3072. xstrlcpy(path, newpath, PATH_MAX);
  3073. lastname[0] = '\0';
  3074. DPRINTF_S(path);
  3075. setdirwatch();
  3076. goto begin;
  3077. case SEL_LEADER: // fallthrough
  3078. case SEL_CYCLE: // fallthrough
  3079. case SEL_CTX1: // fallthrough
  3080. case SEL_CTX2: // fallthrough
  3081. case SEL_CTX3: // fallthrough
  3082. case SEL_CTX4:
  3083. if (sel == SEL_CYCLE)
  3084. fd = '>';
  3085. else if (sel >= SEL_CTX1 && sel <= SEL_CTX4)
  3086. fd = sel - SEL_CTX1 + '1';
  3087. else
  3088. fd = get_input(NULL);
  3089. switch (fd) {
  3090. case 'q': // fallthrough
  3091. case '~': // fallthrough
  3092. case '`': // fallthrough
  3093. case '-': // fallthrough
  3094. case '@':
  3095. presel = fd;
  3096. goto nochange;
  3097. case '>': // fallthrough
  3098. case '.': // fallthrough
  3099. case '<': // fallthrough
  3100. case ',':
  3101. r = cfg.curctx;
  3102. if (fd == '>' || fd == '.')
  3103. do
  3104. r = (r + 1) & ~CTX_MAX;
  3105. while (!g_ctx[r].c_cfg.ctxactive);
  3106. else
  3107. do
  3108. r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
  3109. while (!g_ctx[r].c_cfg.ctxactive); // fallthrough
  3110. fd = '1' + r; // fallthrough
  3111. case '1': // fallthrough
  3112. case '2': // fallthrough
  3113. case '3': // fallthrough
  3114. case '4':
  3115. r = fd - '1'; /* Save the next context id */
  3116. if (cfg.curctx == r) {
  3117. if (sel != SEL_CYCLE)
  3118. continue;
  3119. (r == CTX_MAX - 1) ? (r = 0) : ++r;
  3120. snprintf(newpath, PATH_MAX,
  3121. "Create context %d? [Enter]", r + 1);
  3122. fd = get_input(newpath);
  3123. if (fd != '\r')
  3124. continue;
  3125. }
  3126. savecurctx(&cfg, path, dents[cur].name, r);
  3127. /* Reset the pointers */
  3128. path = g_ctx[r].c_path;
  3129. lastdir = g_ctx[r].c_last;
  3130. lastname = g_ctx[r].c_name;
  3131. setdirwatch();
  3132. goto begin;
  3133. }
  3134. if (!get_bm_loc(newpath, fd)) {
  3135. printwait(messages[STR_INVBM_KEY], &presel);
  3136. goto nochange;
  3137. }
  3138. if (!xdiraccess(newpath))
  3139. goto nochange;
  3140. if (strcmp(path, newpath) == 0)
  3141. break;
  3142. lastname[0] = '\0';
  3143. /* Save last working directory */
  3144. xstrlcpy(lastdir, path, PATH_MAX);
  3145. /* Save the newly opted dir in path */
  3146. xstrlcpy(path, newpath, PATH_MAX);
  3147. DPRINTF_S(path);
  3148. setdirwatch();
  3149. goto begin;
  3150. case SEL_PIN:
  3151. xstrlcpy(mark, path, PATH_MAX);
  3152. printwait(mark, &presel);
  3153. goto nochange;
  3154. case SEL_FLTR:
  3155. /* Unwatch dir if we are still in a filtered view */
  3156. #ifdef LINUX_INOTIFY
  3157. if (inotify_wd >= 0) {
  3158. inotify_rm_watch(inotify_fd, inotify_wd);
  3159. inotify_wd = -1;
  3160. }
  3161. #elif defined(BSD_KQUEUE)
  3162. if (event_fd >= 0) {
  3163. close(event_fd);
  3164. event_fd = -1;
  3165. }
  3166. #endif
  3167. presel = filterentries(path);
  3168. /* Save current */
  3169. if (ndents)
  3170. copycurname();
  3171. if (presel == 27) {
  3172. presel = 0;
  3173. break;
  3174. }
  3175. goto nochange;
  3176. case SEL_MFLTR: // fallthrough
  3177. case SEL_TOGGLEDOT: // fallthrough
  3178. case SEL_DETAIL: // fallthrough
  3179. case SEL_FSIZE: // fallthrough
  3180. case SEL_ASIZE: // fallthrough
  3181. case SEL_BSIZE: // fallthrough
  3182. case SEL_EXTN: // fallthrough
  3183. case SEL_MTIME: // fallthrough
  3184. case SEL_WILD:
  3185. switch (sel) {
  3186. case SEL_MFLTR:
  3187. cfg.filtermode ^= 1;
  3188. if (cfg.filtermode) {
  3189. presel = FILTER;
  3190. goto nochange;
  3191. }
  3192. /* Start watching the directory */
  3193. dir_changed = TRUE;
  3194. break;
  3195. case SEL_TOGGLEDOT:
  3196. cfg.showhidden ^= 1;
  3197. setdirwatch();
  3198. break;
  3199. case SEL_DETAIL:
  3200. cfg.showdetail ^= 1;
  3201. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  3202. continue;
  3203. case SEL_FSIZE:
  3204. cfg.sizeorder ^= 1;
  3205. cfg.mtimeorder = 0;
  3206. cfg.apparentsz = 0;
  3207. cfg.blkorder = 0;
  3208. cfg.extnorder = 0;
  3209. cfg.copymode = 0;
  3210. cfg.wild = 0;
  3211. break;
  3212. case SEL_ASIZE:
  3213. cfg.apparentsz ^= 1;
  3214. if (cfg.apparentsz) {
  3215. nftw_fn = &sum_sizes;
  3216. cfg.blkorder = 1;
  3217. BLK_SHIFT = 0;
  3218. } else
  3219. cfg.blkorder = 0; // fallthrough
  3220. case SEL_BSIZE:
  3221. if (sel == SEL_BSIZE) {
  3222. if (!cfg.apparentsz)
  3223. cfg.blkorder ^= 1;
  3224. nftw_fn = &sum_bsizes;
  3225. cfg.apparentsz = 0;
  3226. BLK_SHIFT = ffs(S_BLKSIZE) - 1;
  3227. }
  3228. if (cfg.blkorder) {
  3229. cfg.showdetail = 1;
  3230. printptr = &printent_long;
  3231. }
  3232. cfg.mtimeorder = 0;
  3233. cfg.sizeorder = 0;
  3234. cfg.extnorder = 0;
  3235. cfg.copymode = 0;
  3236. cfg.wild = 0;
  3237. break;
  3238. case SEL_EXTN:
  3239. cfg.extnorder ^= 1;
  3240. cfg.sizeorder = 0;
  3241. cfg.mtimeorder = 0;
  3242. cfg.apparentsz = 0;
  3243. cfg.blkorder = 0;
  3244. cfg.copymode = 0;
  3245. cfg.wild = 0;
  3246. break;
  3247. case SEL_MTIME:
  3248. cfg.mtimeorder ^= 1;
  3249. cfg.sizeorder = 0;
  3250. cfg.apparentsz = 0;
  3251. cfg.blkorder = 0;
  3252. cfg.extnorder = 0;
  3253. cfg.copymode = 0;
  3254. cfg.wild = 0;
  3255. break;
  3256. default: /* SEL_WILD */
  3257. cfg.wild ^= 1;
  3258. cfg.mtimeorder = 0;
  3259. cfg.sizeorder = 0;
  3260. cfg.apparentsz = 0;
  3261. cfg.blkorder = 0;
  3262. cfg.extnorder = 0;
  3263. cfg.copymode = 0;
  3264. setdirwatch();
  3265. goto nochange;
  3266. }
  3267. /* Save current */
  3268. if (ndents)
  3269. copycurname();
  3270. goto begin;
  3271. case SEL_STATS:
  3272. if (!ndents)
  3273. break;
  3274. mkpath(path, dents[cur].name, newpath);
  3275. if (lstat(newpath, &sb) == -1 || !show_stats(newpath, dents[cur].name, &sb)) {
  3276. printwarn(&presel);
  3277. goto nochange;
  3278. }
  3279. break;
  3280. case SEL_MEDIA: // fallthrough
  3281. case SEL_FMEDIA: // fallthrough
  3282. case SEL_ARCHIVELS: // fallthrough
  3283. case SEL_EXTRACT: // fallthrough
  3284. case SEL_RUNEDIT: // fallthrough
  3285. case SEL_RUNPAGE:
  3286. if (!ndents)
  3287. break; // fallthrough
  3288. case SEL_REDRAW: // fallthrough
  3289. case SEL_RENAMEALL: // fallthrough
  3290. case SEL_HELP: // fallthrough
  3291. case SEL_NOTE: // fallthrough
  3292. case SEL_LOCK:
  3293. {
  3294. if (ndents)
  3295. mkpath(path, dents[cur].name, newpath);
  3296. r = TRUE;
  3297. switch (sel) {
  3298. case SEL_MEDIA: // fallthrough
  3299. case SEL_FMEDIA:
  3300. tmp = (sel == SEL_FMEDIA) ? "-f" : NULL;
  3301. show_mediainfo(newpath, tmp);
  3302. setdirwatch();
  3303. goto nochange;
  3304. case SEL_ARCHIVELS:
  3305. handle_archive(newpath, path, 'l');
  3306. break;
  3307. case SEL_EXTRACT:
  3308. handle_archive(newpath, path, 'x');
  3309. break;
  3310. case SEL_REDRAW:
  3311. if (ndents)
  3312. copycurname();
  3313. goto begin;
  3314. case SEL_RENAMEALL:
  3315. if (!batch_rename(path)) {
  3316. printwait("batch rename failed", &presel);
  3317. goto nochange;
  3318. }
  3319. break;
  3320. case SEL_HELP:
  3321. r = show_help(path);
  3322. break;
  3323. case SEL_RUNEDIT:
  3324. spawn(editor, dents[cur].name, NULL, path, F_CLI);
  3325. break;
  3326. case SEL_RUNPAGE:
  3327. spawn(pager, dents[cur].name, NULL, path, F_CLI);
  3328. break;
  3329. case SEL_NOTE:
  3330. {
  3331. static char *notepath;
  3332. notepath = notepath ? notepath : getenv(env_cfg[NNN_NOTE]);
  3333. if (!notepath) {
  3334. printwait("set NNN_NOTE", &presel);
  3335. goto nochange;
  3336. }
  3337. spawn(editor, notepath, NULL, path, F_CLI);
  3338. break;
  3339. }
  3340. default: /* SEL_LOCK */
  3341. lock_terminal();
  3342. break;
  3343. }
  3344. if (!r) {
  3345. printwait(messages[UTIL_MISSING], &presel);
  3346. goto nochange;
  3347. }
  3348. /* In case of successful operation, reload contents */
  3349. /* Continue in navigate-as-you-type mode, if enabled */
  3350. if (cfg.filtermode)
  3351. presel = FILTER;
  3352. /* Save current */
  3353. if (ndents)
  3354. copycurname();
  3355. /* Repopulate as directory content may have changed */
  3356. goto begin;
  3357. }
  3358. case SEL_COPY:
  3359. if (!ndents)
  3360. goto nochange;
  3361. if (cfg.copymode) {
  3362. /*
  3363. * Clear the selection file on first copy.
  3364. *
  3365. * This ensures that when the first file path is
  3366. * copied into memory (but not written to tmp file
  3367. * yet to save on writes), the tmp file is cleared.
  3368. * The user may be in the middle of selection mode op
  3369. * and issue a cp, mv of multi-rm assuming the files
  3370. * in the copy list would be affected. However, these
  3371. * ops read the source file paths from the tmp file.
  3372. */
  3373. if (!ncp)
  3374. writecp(NULL, 0);
  3375. r = mkpath(path, dents[cur].name, newpath);
  3376. appendfpath(newpath, r);
  3377. ++ncp;
  3378. } else {
  3379. r = mkpath(path, dents[cur].name, newpath);
  3380. if (copybufpos) {
  3381. resetcpind();
  3382. /* Keep the copy buf in sync */
  3383. copybufpos = 0;
  3384. }
  3385. appendfpath(newpath, r);
  3386. writecp(newpath, r - 1); /* Truncate NULL from end */
  3387. spawn(copier, NULL, NULL, NULL, F_NOTRACE);
  3388. }
  3389. dents[cur].flags |= FILE_COPIED;
  3390. break;
  3391. case SEL_COPYMUL:
  3392. cfg.copymode ^= 1;
  3393. if (cfg.copymode) {
  3394. if (copybufpos) {
  3395. resetcpind();
  3396. writecp(NULL, 0);
  3397. copybufpos = 0;
  3398. }
  3399. g_crc = crc8fast((uchar *)dents, ndents * sizeof(struct entry));
  3400. copystartid = cur;
  3401. ncp = 0;
  3402. mvprintw(xlines - 1, 0, "selection on\n");
  3403. xdelay();
  3404. continue;
  3405. }
  3406. if (!ncp) { /* Handle range selection */
  3407. #ifndef DIR_LIMITED_COPY
  3408. if (g_crc != crc8fast((uchar *)dents,
  3409. ndents * sizeof(struct entry))) {
  3410. cfg.copymode = 0;
  3411. printwait("dir/content changed", &presel);
  3412. goto nochange;
  3413. }
  3414. #endif
  3415. if (cur < copystartid) {
  3416. copyendid = copystartid;
  3417. copystartid = cur;
  3418. } else
  3419. copyendid = cur;
  3420. } // fallthrough
  3421. case SEL_COPYALL:
  3422. if (sel == SEL_COPYALL) {
  3423. if (!ndents)
  3424. goto nochange;
  3425. cfg.copymode = 0;
  3426. copybufpos = 0;
  3427. ncp = 0; /* Override single/multi path selection */
  3428. copystartid = 0;
  3429. copyendid = ndents - 1;
  3430. }
  3431. if ((!ncp && copystartid < copyendid) || sel == SEL_COPYALL) {
  3432. for (r = copystartid; r <= copyendid; ++r) {
  3433. appendfpath(newpath, mkpath(path, dents[r].name, newpath));
  3434. dents[r].flags |= FILE_COPIED;
  3435. }
  3436. ncp = copyendid - copystartid + 1;
  3437. mvprintw(xlines - 1, 0, "%d selected\n", ncp);
  3438. xdelay();
  3439. }
  3440. if (copybufpos) { /* File path(s) written to the buffer */
  3441. writecp(pcopybuf, copybufpos - 1); /* Truncate NULL from end */
  3442. spawn(copier, NULL, NULL, NULL, F_NOTRACE);
  3443. if (ncp) { /* Some files cherry picked */
  3444. mvprintw(xlines - 1, 0, "%d selected\n", ncp);
  3445. xdelay();
  3446. }
  3447. } else {
  3448. printwait("selection off", &presel);
  3449. goto nochange;
  3450. }
  3451. continue;
  3452. case SEL_COPYLIST:
  3453. if (showcplist() || showcpfile()) {
  3454. if (cfg.filtermode)
  3455. presel = FILTER;
  3456. break;
  3457. }
  3458. printwait(messages[NONE_SELECTED], &presel);
  3459. goto nochange;
  3460. case SEL_CP:
  3461. case SEL_MV:
  3462. case SEL_RMMUL:
  3463. {
  3464. if (!cpsafe()) {
  3465. presel = MSGWAIT;
  3466. goto nochange;
  3467. }
  3468. switch (sel) {
  3469. case SEL_CP:
  3470. cpstr(g_buf);
  3471. break;
  3472. case SEL_MV:
  3473. mvstr(g_buf);
  3474. break;
  3475. default: /* SEL_RMMUL */
  3476. rmmulstr(g_buf);
  3477. break;
  3478. }
  3479. spawn("sh", "-c", g_buf, path, F_NORMAL);
  3480. if (ndents)
  3481. copycurname();
  3482. if (cfg.filtermode)
  3483. presel = FILTER;
  3484. goto begin;
  3485. }
  3486. case SEL_RM:
  3487. {
  3488. if (!ndents)
  3489. break;
  3490. mkpath(path, dents[cur].name, newpath);
  3491. xrm(newpath);
  3492. /* Don't optimize cur if filtering is on */
  3493. if (!cfg.filtermode && cur && access(newpath, F_OK) == -1)
  3494. move_cursor(cur - 1, 0);
  3495. /* We reduce cur only if it is > 0, so it's at least 0 */
  3496. copycurname();
  3497. if (cfg.filtermode)
  3498. presel = FILTER;
  3499. goto begin;
  3500. }
  3501. case SEL_OPENWITH: // fallthrough
  3502. case SEL_RENAME:
  3503. if (!ndents)
  3504. break; // fallthrough
  3505. case SEL_ARCHIVE: // fallthrough
  3506. case SEL_NEW:
  3507. {
  3508. int dup = 'n';
  3509. switch (sel) {
  3510. case SEL_ARCHIVE:
  3511. r = get_input("archive selection (else current)? [y/Y confirms]");
  3512. if (r == 'y' || r == 'Y') {
  3513. if (!cpsafe()) {
  3514. presel = MSGWAIT;
  3515. goto nochange;
  3516. }
  3517. tmp = NULL;
  3518. } else if (!ndents) {
  3519. printwait("no files", &presel);
  3520. goto nochange;
  3521. } else
  3522. tmp = dents[cur].name;
  3523. tmp = xreadline(tmp, "archive name: ");
  3524. break;
  3525. case SEL_OPENWITH:
  3526. #ifdef NORL
  3527. tmp = xreadline(NULL, "open with: ");
  3528. #else
  3529. presel = 0;
  3530. tmp = getreadline("open with: ", path, ipath, &presel);
  3531. if (presel == MSGWAIT)
  3532. goto nochange;
  3533. #endif
  3534. break;
  3535. case SEL_NEW:
  3536. tmp = xreadline(NULL, "name/link suffix [@ for none]: ");
  3537. break;
  3538. default: /* SEL_RENAME */
  3539. dup = get_input("Press 'r'(ename) / 'd'(uplicate)");
  3540. if (dup == 'r' || dup == 'd') {
  3541. tmp = xreadline(dents[cur].name, "");
  3542. break;
  3543. }
  3544. tmp = NULL;
  3545. }
  3546. if (!tmp || !*tmp)
  3547. break;
  3548. /* Allow only relative, same dir paths */
  3549. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  3550. printwait(messages[STR_INPUT_ID], &presel);
  3551. goto nochange;
  3552. }
  3553. /* Confirm if app is CLI or GUI */
  3554. if (sel == SEL_OPENWITH) {
  3555. r = get_input("cli mode? [y/Y confirms]");
  3556. (r == 'y' || r == 'Y') ? (r = F_CLI)
  3557. : (r = F_NOWAIT | F_NOTRACE | F_MULTI);
  3558. }
  3559. switch (sel) {
  3560. case SEL_ARCHIVE:
  3561. {
  3562. char cmd[ARCHIVE_CMD_LEN];
  3563. get_archive_cmd(cmd, tmp);
  3564. (r == 'y' || r == 'Y') ? archive_selection(cmd, tmp, path)
  3565. : spawn(cmd, tmp, dents[cur].name,
  3566. path, F_NORMAL | F_MULTI);
  3567. break;
  3568. }
  3569. case SEL_OPENWITH:
  3570. mkpath(path, dents[cur].name, newpath);
  3571. spawn(tmp, newpath, NULL, path, r);
  3572. break;
  3573. case SEL_RENAME:
  3574. /* Skip renaming to same name */
  3575. if (strcmp(tmp, dents[cur].name) == 0)
  3576. goto nochange;
  3577. break;
  3578. default:
  3579. break;
  3580. }
  3581. /* Complete OPEN, LAUNCH, ARCHIVE operations */
  3582. if (sel != SEL_NEW && sel != SEL_RENAME) {
  3583. /* Continue in navigate-as-you-type mode, if enabled */
  3584. if (cfg.filtermode)
  3585. presel = FILTER;
  3586. /* Save current */
  3587. copycurname();
  3588. /* Repopulate as directory content may have changed */
  3589. goto begin;
  3590. }
  3591. /* Open the descriptor to currently open directory */
  3592. fd = open(path, O_RDONLY | O_DIRECTORY);
  3593. if (fd == -1) {
  3594. printwarn(&presel);
  3595. goto nochange;
  3596. }
  3597. /* Check if another file with same name exists */
  3598. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  3599. if (sel == SEL_RENAME) {
  3600. /* Overwrite file with same name? */
  3601. r = get_input("overwrite? [y/Y confirms]");
  3602. if (r != 'y' && r != 'Y') {
  3603. close(fd);
  3604. break;
  3605. }
  3606. } else {
  3607. /* Do nothing in case of NEW */
  3608. close(fd);
  3609. printwait("entry exists", &presel);
  3610. goto nochange;
  3611. }
  3612. }
  3613. if (sel == SEL_RENAME) {
  3614. /* Rename the file */
  3615. if (dup == 'd')
  3616. spawn("cp -r", dents[cur].name, tmp, path, F_CLI | F_NOTRACE);
  3617. else if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  3618. close(fd);
  3619. printwarn(&presel);
  3620. goto nochange;
  3621. }
  3622. } else {
  3623. /* Check if it's a dir or file */
  3624. r = get_input("create 'f'(ile) / 'd'(ir) / 's'(ym) / 'h'(ard)?");
  3625. if (r == 'f') {
  3626. r = openat(fd, tmp, O_CREAT, 0666);
  3627. close(r);
  3628. } else if (r == 'd') {
  3629. r = mkdirat(fd, tmp, 0777);
  3630. } else if (r == 's' || r == 'h') {
  3631. if (tmp[0] == '@' && tmp[1] == '\0')
  3632. tmp[0] = '\0';
  3633. r = xlink(tmp, path, newpath, &presel, r);
  3634. close(fd);
  3635. if (r <= 0)
  3636. goto nochange;
  3637. if (cfg.filtermode)
  3638. presel = FILTER;
  3639. if (ndents)
  3640. copycurname();
  3641. goto begin;
  3642. } else {
  3643. close(fd);
  3644. break;
  3645. }
  3646. /* Check if file creation failed */
  3647. if (r == -1) {
  3648. printwarn(&presel);
  3649. close(fd);
  3650. goto nochange;
  3651. }
  3652. }
  3653. close(fd);
  3654. xstrlcpy(lastname, tmp, NAME_MAX + 1);
  3655. goto begin;
  3656. }
  3657. case SEL_EXEC: // fallthrough
  3658. case SEL_SHELL: // fallthrough
  3659. case SEL_PLUGIN: // fallthrough
  3660. case SEL_LAUNCH: // fallthrough
  3661. case SEL_RUNCMD:
  3662. switch (sel) {
  3663. case SEL_EXEC:
  3664. if (!execute_file(cur, path, newpath, &presel))
  3665. goto nochange;
  3666. break;
  3667. case SEL_SHELL:
  3668. spawn(shell, NULL, NULL, path, F_CLI);
  3669. break;
  3670. case SEL_PLUGIN:
  3671. if (!plugindir) {
  3672. printwait("plugins dir missing", &presel);
  3673. goto nochange;
  3674. }
  3675. if (stat(plugindir, &sb) == -1) {
  3676. printwarn(&presel);
  3677. goto nochange;
  3678. }
  3679. /* Must be a directory */
  3680. if (!S_ISDIR(sb.st_mode))
  3681. break;
  3682. cfg.runplugin ^= 1;
  3683. if (!cfg.runplugin && rundir[0]) {
  3684. /*
  3685. * If toggled, and still in the plugin dir,
  3686. * switch to original directory
  3687. */
  3688. if (strcmp(path, plugindir) == 0) {
  3689. xstrlcpy(path, rundir, PATH_MAX);
  3690. xstrlcpy(lastname, runfile, NAME_MAX);
  3691. rundir[0] = runfile[0] = '\0';
  3692. setdirwatch();
  3693. goto begin;
  3694. }
  3695. break;
  3696. }
  3697. /* Check if directory is accessible */
  3698. if (!xdiraccess(plugindir))
  3699. goto nochange;
  3700. xstrlcpy(rundir, path, PATH_MAX);
  3701. xstrlcpy(path, plugindir, PATH_MAX);
  3702. if (ndents)
  3703. xstrlcpy(runfile, dents[cur].name, NAME_MAX);
  3704. cfg.runctx = cfg.curctx;
  3705. lastname[0] = '\0';
  3706. setdirwatch();
  3707. goto begin;
  3708. case SEL_LAUNCH:
  3709. if (getutil(utils[NLAUNCH])) {
  3710. spawn(utils[NLAUNCH], "0", NULL, path, F_NORMAL);
  3711. break;
  3712. } // fallthrough
  3713. default: /* SEL_RUNCMD */
  3714. #ifndef NORL
  3715. if (cfg.picker) {
  3716. #endif
  3717. tmp = xreadline(NULL, "> ");
  3718. #ifndef NORL
  3719. } else {
  3720. presel = 0;
  3721. tmp = getreadline("> ", path, ipath, &presel);
  3722. if (presel == MSGWAIT)
  3723. goto nochange;
  3724. }
  3725. #endif
  3726. if (tmp && tmp[0]) // NOLINT
  3727. spawn(shell, "-c", tmp, path, F_CLI | F_CMD);
  3728. }
  3729. /* Continue in navigate-as-you-type mode, if enabled */
  3730. if (cfg.filtermode)
  3731. presel = FILTER;
  3732. /* Save current */
  3733. if (ndents)
  3734. copycurname();
  3735. /* Repopulate as directory content may have changed */
  3736. goto begin;
  3737. case SEL_SSHFS:
  3738. if (!sshfs_mount(path, newpath, &presel))
  3739. goto nochange;
  3740. lastname[0] = '\0';
  3741. /* Save last working directory */
  3742. xstrlcpy(lastdir, path, PATH_MAX);
  3743. /* Switch to mount point */
  3744. xstrlcpy(path, newpath, PATH_MAX);
  3745. setdirwatch();
  3746. goto begin;
  3747. case SEL_UMOUNT:
  3748. sshfs_unmount(path, newpath, &presel);
  3749. goto nochange;
  3750. case SEL_QUITCD: // fallthrough
  3751. case SEL_QUIT:
  3752. for (r = 0; r < CTX_MAX; ++r)
  3753. if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
  3754. r = get_input("Quit all contexts? [Enter]");
  3755. break;
  3756. }
  3757. if (!(r == CTX_MAX || r == '\r'))
  3758. break;
  3759. if (sel == SEL_QUITCD) {
  3760. /* In vim picker mode, clear selection and exit */
  3761. if (cfg.picker) {
  3762. /* Picker mode: reset buffer or clear file */
  3763. if (copybufpos)
  3764. cfg.pickraw ? copybufpos = 0 : writecp(NULL, 0);
  3765. } else if (!write_lastdir(path)) {
  3766. presel = MSGWAIT;
  3767. goto nochange;
  3768. }
  3769. }
  3770. return;
  3771. case SEL_QUITCTX:
  3772. fd = cfg.curctx; /* fd used as tmp var */
  3773. for (r = (fd + 1) & ~CTX_MAX;
  3774. (r != fd) && !g_ctx[r].c_cfg.ctxactive;
  3775. r = ((r + 1) & ~CTX_MAX)) {
  3776. };
  3777. if (r != fd) {
  3778. bool copymode = cfg.copymode ? TRUE : FALSE;
  3779. g_ctx[fd].c_cfg.ctxactive = 0;
  3780. /* Switch to next active context */
  3781. path = g_ctx[r].c_path;
  3782. lastdir = g_ctx[r].c_last;
  3783. lastname = g_ctx[r].c_name;
  3784. /* Switch light/detail mode */
  3785. if (cfg.showdetail != g_ctx[r].c_cfg.showdetail)
  3786. /* Set the reverse */
  3787. printptr = cfg.showdetail ? &printent : &printent_long;
  3788. cfg = g_ctx[r].c_cfg;
  3789. /* Continue copy mode */
  3790. cfg.copymode = copymode;
  3791. cfg.curctx = r;
  3792. setdirwatch();
  3793. goto begin;
  3794. }
  3795. return;
  3796. default:
  3797. if (xlines != LINES || xcols != COLS) {
  3798. idle = 0;
  3799. setdirwatch();
  3800. if (ndents)
  3801. copycurname();
  3802. goto begin;
  3803. }
  3804. /* Locker */
  3805. if (idletimeout && idle == idletimeout) {
  3806. idle = 0;
  3807. lock_terminal();
  3808. if (ndents)
  3809. copycurname();
  3810. goto begin;
  3811. }
  3812. goto nochange;
  3813. } /* switch (sel) */
  3814. }
  3815. }
  3816. static void usage(void)
  3817. {
  3818. fprintf(stdout,
  3819. "%s: nnn [-b key] [-d] [-e] [-H] [-i] [-n]\n"
  3820. " [-p file] [-s] [-S] [-v] [-w] [-h] [PATH]\n\n"
  3821. "The missing terminal file manager for X.\n\n"
  3822. "positional args:\n"
  3823. " PATH start dir [default: current dir]\n\n"
  3824. "optional args:\n"
  3825. " -b key open bookmark key\n"
  3826. " -d detail mode\n"
  3827. " -e use exiftool for media info\n"
  3828. " -H show hidden files\n"
  3829. " -i nav-as-you-type mode\n"
  3830. " -n version sort\n"
  3831. " -p file selection file (stdout if '-')\n"
  3832. " -s string filters [default: regex]\n"
  3833. " -S du mode\n"
  3834. " -v show version\n"
  3835. " -w wild load\n"
  3836. " -h show help\n\n"
  3837. "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
  3838. }
  3839. static bool setup_config(void)
  3840. {
  3841. size_t r, len;
  3842. char *xdgcfg = getenv("XDG_CONFIG_HOME");
  3843. bool xdg = FALSE;
  3844. /* Set up configuration file paths */
  3845. if (xdgcfg && xdgcfg[0]) {
  3846. DPRINTF_S(xdgcfg);
  3847. if (xdgcfg[0] == '~') {
  3848. r = xstrlcpy(g_buf, home, PATH_MAX);
  3849. xstrlcpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
  3850. xdgcfg = g_buf;
  3851. DPRINTF_S(xdgcfg);
  3852. }
  3853. if (!xdiraccess(xdgcfg)) {
  3854. xerror();
  3855. return FALSE;
  3856. }
  3857. len = strlen(xdgcfg) + 1 + 12; /* add length of "/nnn/plugins" */
  3858. xdg = TRUE;
  3859. }
  3860. if (!xdg)
  3861. len = strlen(home) + 1 + 20; /* add length of "/.config/nnn/plugins" */
  3862. cfgdir = (char *)malloc(len);
  3863. plugindir = (char *)malloc(len);
  3864. if (!cfgdir || !plugindir) {
  3865. xerror();
  3866. return FALSE;
  3867. }
  3868. if (xdg) {
  3869. xstrlcpy(cfgdir, xdgcfg, len);
  3870. r = len - 12;
  3871. } else {
  3872. r = xstrlcpy(cfgdir, home, len);
  3873. /* Create ~/.config */
  3874. xstrlcpy(cfgdir + r - 1, "/.config", len - r);
  3875. DPRINTF_S(cfgdir);
  3876. if (!create_dir(cfgdir)) {
  3877. xerror();
  3878. return FALSE;
  3879. }
  3880. r += 8; /* length of "/.config" */
  3881. }
  3882. /* Create ~/.config/nnn */
  3883. xstrlcpy(cfgdir + r - 1, "/nnn", len - r);
  3884. DPRINTF_S(cfgdir);
  3885. if (!create_dir(cfgdir)) {
  3886. xerror();
  3887. return FALSE;
  3888. }
  3889. /* Create ~/.config/nnn/plugins */
  3890. xstrlcpy(cfgdir + r + 4 - 1, "/plugins", 9);
  3891. DPRINTF_S(cfgdir);
  3892. xstrlcpy(plugindir, cfgdir, len);
  3893. DPRINTF_S(plugindir);
  3894. if (!create_dir(cfgdir)) {
  3895. xerror();
  3896. return FALSE;
  3897. }
  3898. /* Reset to config path */
  3899. cfgdir[r + 3] = '\0';
  3900. DPRINTF_S(cfgdir);
  3901. /* Set selection file path */
  3902. if (!cfg.picker) {
  3903. /* Length of "/.config/nnn/.selection" */
  3904. g_cppath = (char *)malloc(len + 3);
  3905. r = xstrlcpy(g_cppath, cfgdir, len + 3);
  3906. xstrlcpy(g_cppath + r - 1, "/.selection", 12);
  3907. DPRINTF_S(g_cppath);
  3908. }
  3909. return TRUE;
  3910. }
  3911. static bool set_tmp_path()
  3912. {
  3913. char *path;
  3914. if (xdiraccess("/tmp"))
  3915. g_tmpfplen = xstrlcpy(g_tmpfpath, "/tmp", TMP_LEN_MAX);
  3916. else {
  3917. path = getenv("TMPDIR");
  3918. if (path)
  3919. g_tmpfplen = xstrlcpy(g_tmpfpath, path, TMP_LEN_MAX);
  3920. else {
  3921. fprintf(stderr, "set TMPDIR\n");
  3922. return FALSE;
  3923. }
  3924. }
  3925. return TRUE;
  3926. }
  3927. static void cleanup(void)
  3928. {
  3929. free(g_cppath);
  3930. free(plugindir);
  3931. free(cfgdir);
  3932. free(initpath);
  3933. #ifdef DBGMODE
  3934. disabledbg();
  3935. #endif
  3936. }
  3937. int main(int argc, char *argv[])
  3938. {
  3939. char *arg = NULL;
  3940. int opt;
  3941. while ((opt = getopt(argc, argv, "HSib:denp:svwh")) != -1) {
  3942. switch (opt) {
  3943. case 'S':
  3944. cfg.blkorder = 1;
  3945. nftw_fn = sum_bsizes;
  3946. BLK_SHIFT = ffs(S_BLKSIZE) - 1;
  3947. break;
  3948. case 'd':
  3949. cfg.showdetail = 1;
  3950. printptr = &printent_long;
  3951. break;
  3952. case 'i':
  3953. cfg.filtermode = 1;
  3954. break;
  3955. case 'b':
  3956. arg = optarg;
  3957. break;
  3958. case 'e':
  3959. cfg.metaviewer = EXIFTOOL;
  3960. break;
  3961. case 'H':
  3962. cfg.showhidden = 1;
  3963. break;
  3964. case 'n':
  3965. cmpfn = &xstrverscasecmp;
  3966. break;
  3967. case 'p':
  3968. cfg.picker = 1;
  3969. if (optarg[0] == '-' && optarg[1] == '\0')
  3970. cfg.pickraw = 1;
  3971. else {
  3972. int fd = open(optarg, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
  3973. if (fd == -1) {
  3974. xerror();
  3975. return _FAILURE;
  3976. }
  3977. close(fd);
  3978. g_cppath = realpath(optarg, NULL);
  3979. unlink(g_cppath);
  3980. }
  3981. break;
  3982. case 's':
  3983. cfg.filter_re = 0;
  3984. filterfn = &visible_str;
  3985. break;
  3986. case 'v':
  3987. fprintf(stdout, "%s\n", VERSION);
  3988. return _SUCCESS;
  3989. case 'w':
  3990. cfg.wild = 1;
  3991. break;
  3992. case 'h':
  3993. usage();
  3994. return _SUCCESS;
  3995. default:
  3996. usage();
  3997. return _FAILURE;
  3998. }
  3999. }
  4000. /* Confirm we are in a terminal */
  4001. if (!cfg.picker && !(isatty(0) && isatty(1)))
  4002. exit(1);
  4003. /* Get the context colors; copier used as tmp var */
  4004. copier = xgetenv(env_cfg[NNN_CONTEXT_COLORS], "4444");
  4005. opt = 0;
  4006. while (opt < CTX_MAX) {
  4007. if (*copier) {
  4008. if (*copier < '0' || *copier > '7') {
  4009. fprintf(stderr, "0 <= code <= 7\n");
  4010. return _FAILURE;
  4011. }
  4012. g_ctx[opt].color = *copier - '0';
  4013. ++copier;
  4014. } else
  4015. g_ctx[opt].color = 4;
  4016. ++opt;
  4017. }
  4018. #ifdef DBGMODE
  4019. enabledbg();
  4020. #endif
  4021. atexit(cleanup);
  4022. home = getenv("HOME");
  4023. if (!home) {
  4024. fprintf(stderr, "set HOME\n");
  4025. return _FAILURE;
  4026. }
  4027. DPRINTF_S(home);
  4028. if (!setup_config())
  4029. return _FAILURE;
  4030. /* Get custom opener, if set */
  4031. opener = xgetenv(env_cfg[NNN_OPENER], utils[OPENER]);
  4032. DPRINTF_S(opener);
  4033. /* Parse bookmarks string */
  4034. if (!parsebmstr()) {
  4035. fprintf(stderr, "%s\n", env_cfg[NNN_BMS]);
  4036. return _FAILURE;
  4037. }
  4038. if (arg) { /* Open a bookmark directly */
  4039. if (arg[1] || (initpath = get_bm_loc(NULL, *arg)) == NULL) {
  4040. fprintf(stderr, "%s\n", messages[STR_INVBM_KEY]);
  4041. return _FAILURE;
  4042. }
  4043. } else if (argc == optind) {
  4044. /* Start in the current directory */
  4045. initpath = getcwd(NULL, PATH_MAX);
  4046. if (!initpath)
  4047. initpath = "/";
  4048. } else {
  4049. arg = argv[optind];
  4050. if (strlen(arg) > 7 && arg[0] == 'f' && arg[1] == 'i' && arg[2] == 'l'
  4051. && arg[3] == 'e' && arg[4] == ':' && arg[5] == '/' && arg[6] == '/')
  4052. arg = arg + 7;
  4053. initpath = realpath(arg, NULL);
  4054. DPRINTF_S(initpath);
  4055. if (!initpath) {
  4056. xerror();
  4057. return _FAILURE;
  4058. }
  4059. /*
  4060. * If nnn is set as the file manager, applications may try to open
  4061. * files by invoking nnn. In that case pass the file path to the
  4062. * desktop opener and exit.
  4063. */
  4064. struct stat sb;
  4065. if (stat(initpath, &sb) == -1) {
  4066. xerror();
  4067. return _FAILURE;
  4068. }
  4069. if (S_ISREG(sb.st_mode)) {
  4070. execlp(opener, opener, arg, NULL);
  4071. return _SUCCESS;
  4072. }
  4073. }
  4074. /* Edit text in EDITOR, if opted */
  4075. if (xgetenv_set(env_cfg[NNN_USE_EDITOR]))
  4076. cfg.useeditor = 1;
  4077. /* Get VISUAL/EDITOR */
  4078. editor = xgetenv(envs[VISUAL], xgetenv(envs[EDITOR], "vi"));
  4079. DPRINTF_S(getenv(envs[VISUAL]));
  4080. DPRINTF_S(getenv(envs[EDITOR]));
  4081. DPRINTF_S(editor);
  4082. /* Get PAGER */
  4083. pager = xgetenv(envs[PAGER], "less");
  4084. DPRINTF_S(pager);
  4085. /* Get SHELL */
  4086. shell = xgetenv(envs[SHELL], "sh");
  4087. DPRINTF_S(shell);
  4088. DPRINTF_S(getenv("PWD"));
  4089. #ifdef LINUX_INOTIFY
  4090. /* Initialize inotify */
  4091. inotify_fd = inotify_init1(IN_NONBLOCK);
  4092. if (inotify_fd < 0) {
  4093. xerror();
  4094. return _FAILURE;
  4095. }
  4096. #elif defined(BSD_KQUEUE)
  4097. kq = kqueue();
  4098. if (kq < 0) {
  4099. xerror();
  4100. return _FAILURE;
  4101. }
  4102. #endif
  4103. /* Set nnn nesting level, idletimeout used as tmp var */
  4104. idletimeout = xatoi(getenv(env_cfg[NNNLVL]));
  4105. setenv(env_cfg[NNNLVL], xitoa(++idletimeout), 1);
  4106. /* Get locker wait time, if set */
  4107. idletimeout = xatoi(getenv(env_cfg[NNN_IDLE_TIMEOUT]));
  4108. DPRINTF_U(idletimeout);
  4109. if (xgetenv_set(env_cfg[NNN_TRASH]))
  4110. cfg.trash = 1;
  4111. /* Prefix for temporary files */
  4112. if (!set_tmp_path())
  4113. return _FAILURE;
  4114. /* Get the clipboard copier, if set */
  4115. copier = getenv(env_cfg[NNN_COPIER]);
  4116. /* Disable auto-select if opted */
  4117. if (xgetenv_set(env_cfg[NNN_NO_AUTOSELECT]))
  4118. cfg.autoselect = 0;
  4119. /* Disable opening files on right arrow and `l` */
  4120. if (xgetenv_set(env_cfg[NNN_RESTRICT_NAV_OPEN]))
  4121. cfg.nonavopen = 1;
  4122. #ifdef __linux__
  4123. if (!xgetenv_set(env_cfg[NNN_OPS_PROG])) {
  4124. cp[5] = cp[4];
  4125. cp[2] = cp[4] = ' ';
  4126. mv[5] = mv[4];
  4127. mv[2] = mv[4] = ' ';
  4128. }
  4129. #endif
  4130. /* Ignore/handle certain signals */
  4131. struct sigaction act = {.sa_handler = sigint_handler};
  4132. if (sigaction(SIGINT, &act, NULL) < 0) {
  4133. xerror();
  4134. return _FAILURE;
  4135. }
  4136. signal(SIGQUIT, SIG_IGN);
  4137. /* Test initial path */
  4138. if (!xdiraccess(initpath)) {
  4139. xerror();
  4140. return _FAILURE;
  4141. }
  4142. /* Set locale */
  4143. setlocale(LC_ALL, "");
  4144. #ifndef NORL
  4145. #if RL_READLINE_VERSION >= 0x0603
  4146. /* readline would overwrite the WINCH signal hook */
  4147. rl_change_environment = 0;
  4148. #endif
  4149. /* Bind TAB to cycling */
  4150. rl_variable_bind("completion-ignore-case", "on");
  4151. #ifdef __linux__
  4152. rl_bind_key('\t', rl_menu_complete);
  4153. #else
  4154. rl_bind_key('\t', rl_complete);
  4155. #endif
  4156. read_history(NULL);
  4157. #endif
  4158. if (!initcurses())
  4159. return _FAILURE;
  4160. browse(initpath);
  4161. exitcurses();
  4162. #ifndef NORL
  4163. write_history(NULL);
  4164. #endif
  4165. if (cfg.pickraw) {
  4166. if (copybufpos) {
  4167. opt = selectiontofd(1, NULL);
  4168. if (opt != (int)(copybufpos))
  4169. xerror();
  4170. }
  4171. } else if (!cfg.picker && g_cppath)
  4172. unlink(g_cppath);
  4173. /* Free the copy buffer */
  4174. free(pcopybuf);
  4175. #ifdef LINUX_INOTIFY
  4176. /* Shutdown inotify */
  4177. if (inotify_wd >= 0)
  4178. inotify_rm_watch(inotify_fd, inotify_wd);
  4179. close(inotify_fd);
  4180. #elif defined(BSD_KQUEUE)
  4181. if (event_fd >= 0)
  4182. close(event_fd);
  4183. close(kq);
  4184. #endif
  4185. return _SUCCESS;
  4186. }