My build of nnn with minor changes
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

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