My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

3545 lines
79 KiB

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