My build of nnn with minor changes
 
 
 
 
 
 

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