My build of nnn with minor changes
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

3540 wiersze
79 KiB

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