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.
 
 
 
 
 
 

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