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.
 
 
 
 
 
 

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